您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C++怎么使用有符號數(shù)進行數(shù)學(xué)運算”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
ES.102:使用有符號數(shù)進行數(shù)學(xué)運算
因為大部分數(shù)學(xué)運算都是有符號的。當(dāng)x>y時,x-y會返回一個負數(shù),極少情況實際需要的是按模運算。
Example(示例)
如果不是你有意為之,無符號運算可能產(chǎn)生意外的結(jié)果。如果混用有符號數(shù)和無符號數(shù),問題會更明顯。
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
}
代碼中我們已經(jīng)很明確地知道發(fā)生了什么。但是如果你看到us - (s + 2) or s += 2; ...; us - s,你真的可以想象結(jié)果是4294967294么?
Exception(例外)
如果你真的需要按模運算-增加必要的注釋提示對溢出行為的依賴,這樣的代碼會令很多程序員疑惑。
Example(示例)
標(biāo)準庫使用無符號類型作為下標(biāo)。內(nèi)置數(shù)組使用有符號數(shù)作為下標(biāo)。這會導(dǎo)致代碼難于理解并不可避免地帶來錯誤。
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作為下標(biāo)。
Enforcement(實施建議)
Flag mixed signed and unsigned arithmetic
標(biāo)記有符號數(shù)和無符號數(shù)混用的數(shù)學(xué)運算。
Flag results of unsigned arithmetic assigned to or printed as signed.
標(biāo)記將無符號數(shù)學(xué)運算的結(jié)果賦值給有符號數(shù)或者作為有符號數(shù)print輸出的情況。
Flag negative literals (e.g. -2) used as container subscripts.
標(biāo)記使用負值作為容器下標(biāo)的情況。
(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.
(為了避免誤判)當(dāng)一個參數(shù)是sizeof或者container.size()的返回值,而另一個參數(shù)是ptrdiff_t的時候,不要標(biāo)記有符號數(shù)/無符號數(shù)混合的比較操作。
“C++怎么使用有符號數(shù)進行數(shù)學(xué)運算”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。