看板 C_and_CPP 關於我們 聯絡資訊
遇到的問題: (題意請描述清楚) 我用 unsigned long long 定義我的函式, 這樣它的輸出範圍應該能到 0~2^64, 也就是至少能輸出19位, 但是實際計算,輸出後發現它到10位數後計算就錯誤了, 請問這是什麼原因?是溢位嘛? 該如何解決?謝謝! 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Dev-C++ 有問題的code: (請善用置底文標色功能) #include<iostream> #include<iomanip> using namespace std; unsigned long long sum( unsigned int n )//只能算10位? { return ( n + 1 ) * ( n ) / 2; //梯形公式 } int main() { unsigned int n = 100000; //6位 cout << setw(20) << sum(n) << endl; //溢位了? system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.85.191.24
nowar100:你拿unsigned int在運算,早就溢位了 08/21 10:10
nowar100:還有輸出範圍應該是0~2^64-1 08/21 10:11
Cidolfas:3Q,也就是說在此例函式裡變數的定義要跟函式一樣? 08/21 11:21
Cidolfas:因為原本我想說 n 最多輸出值也只到int範圍,想省一點 08/21 11:22
hilorrk:可以在運算時轉型 08/21 11:25
VictorTom:是跟函式的回傳值一樣喔@_@" 另外, 幾個uint的operand 08/21 11:29
VictorTom:互相做運算, 不先做強制轉型結果也仍是uint, 你的問題 08/21 11:30
VictorTom:和置底十誡之八的一個例子差不多: 08/21 11:31
VictorTom:float f = 10/3; // 會算出f為3.0而不是3.3333差不多. 08/21 11:32