當我執行此代碼時, 的ans1值ans2是50002896和50005000。
我知道功能存在一些問題,ceil但無法找出確切原因。
#include <bits/stdc .h>
using namespace std;
int main()
{
long long ans1 = 0, ans2 = 0;
for (long long i = 1; i <= 10000; i )
{
ans1 = ans1 ceil((float)i / 1);
ans2 = ans2 i;
}
cout << ans1 << " " << ans2 << endl;
}
uj5u.com熱心網友回復:
問題的根源不是ceil函式,而是并非所有整數都可以準確地表示為浮點值。有關浮點表示的更多資訊:Wikipedia IEEE 754。
以下代碼是導致您的問題的同一問題的最小演示:
float f1 = 100000000;
f1 ;
std::cout << std::to_string(f1) << std::endl;
[錯誤] 輸出(預期: 1):
100000000.000000
一種方法是使用double而不是float.
這不會解決原則問題,但會使可表示整數的范圍更大:
double f1 = 100000000;
f1 ;
std::cout << std::to_string(f1) << std::endl;
輸出:
100000001.000000
旁注:最好避免#include <bits/stdc .h>,請參閱:Why should I not #include <bits/stdc .h>? .
uj5u.com熱心網友回復:
首先,嘗試使用像 #include 這樣的特定標頭,在這種情況下,.because #include <bits/stdc .h> 會帶來很多垃圾。
所以問題是 float 而不是 ceil 解釋如下
浮點值不代表精確值。
代碼:-
#include <iostream>
#include <iomanip>
using namespace std;
// Driver Code
int main()
{
float num1 = 10000.29;
float num2 = 10000.2;
// Output should be 0.0900000000
cout << std::setprecision(15)
<< (num1 - num2);
return 0;
}
輸出 :-
0.08984375
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537148.html
標籤:C C 11浮点天花板
