重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

C++怎么使用有符号数进行数学运算

本篇内容介绍了“C++怎么使用有符号数进行数学运算”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

专注于为中小企业提供成都做网站、成都网站建设、成都外贸网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业藤县免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了千余家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

ES.102:使用有符号数进行数学运算

Reason(原因)

因为大部分数学运算都是有符号的。当x>y时,x-y会返回一个负数,极少情况实际需要的是按模运算。

Example(示例)

如果不是你有意为之,无符号运算可能产生意外的结果。如果混用有符号数和无符号数,问题会更明显。

template
T subtract(T x, T2 y)
{
   return x - y;
}

void test()
{
   int s = 5;
   unsigned int us = 5;
   cout << subtract(s, 7) << '\n';       // -2
   cout << subtract(us, 7u) << '\n';     // 4294967294
   cout << subtract(s, 7u) << '\n';      // -2
   cout << subtract(us, 7) << '\n';      // 4294967294
   cout << subtract(s, us + 2) << '\n';  // -2
   cout << subtract(us, s + 2) << '\n';  // 4294967294
}

代码中我们已经很明确地知道发生了什么。但是如果你看到us - (s + 2) or s += 2; ...; us - s,你真的可以想象结果是4294967294么?

Exception(例外)

如果你真的需要按模运算-增加必要的注释提示对溢出行为的依赖,这样的代码会令很多程序员疑惑。

Example(示例)

标准库使用无符号类型作为下标。内置数组使用有符号数作为下标。这会导致代码难于理解并不可避免地带来错误。

int a[10];
for (int i = 0; i < 10; ++i) a[i] = i;
vector v(10);
// compares signed to unsigned; some compilers warn, but we should not
for (gsl::index i = 0; i < v.size(); ++i) v[i] = i;

int a2[-2];         // error: negative size

// OK, but the number of ints (4294967294) is so large that we should get an exception
vector v2(-2);

Use gsl::index for subscripts; see ES.107.

使用ES.107中介绍的gsl::index作为下标。

Enforcement(实施建议)

  • Flag mixed signed and unsigned arithmetic

  • 标记有符号数和无符号数混用的数学运算。

  • Flag results of unsigned arithmetic assigned to or printed as signed.

  • 标记将无符号数学运算的结果赋值给有符号数或者作为有符号数print输出的情况。

  • Flag negative literals (e.g. -2) used as container subscripts.

  • 标记使用负值作为容器下标的情况。

  • (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is sizeof or a call to container .size() and the other is ptrdiff_t.

  • (为了避免误判)当一个参数是sizeof或者container.size()的返回值,而另一个参数是ptrdiff_t的时候,不要标记有符号数/无符号数混合的比较操作。

“C++怎么使用有符号数进行数学运算”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


当前文章:C++怎么使用有符号数进行数学运算
文章分享:http://cqcxhl.com/article/giojcp.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP