温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-25 16:24:50 来源:亿速云 阅读:204 作者:iii 栏目:大数据

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

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

Reason(原因)

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

Example(示例)

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

template<typename T, typename T2>
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<int> 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<int> 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++怎么使用有符号数进行数学运算”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI