2017-02-17 39 views
0

我在做一個程序,它首先從用戶處獲得2個數字(包含float數據類型),然後詢問用戶想要得到的數字是多少,最後將其分開最多到這個數字和'cout < <'它。它編譯但沒有做到 - 當我計算22/7這個標記時,這是一個非理性的否定。最多可計算100位數字,最多可達30位或40位數字,其餘部分填充零。事情是這樣的: 3.1428570747375488281250000000000000000000000000000000000000000000000000000000000000000000000000000000setprecision()不能按預期工作

這裏是我的代碼:

#include <iostream> 
#include <cstdlib> 
#include <iomanip> 
using namespace std; 
int main() 
{ 
    system("clear"); 
    float y; 
    int z; 
    float x; 
    float a; 
    cout << "\nHello User\n"; 
    cout << "\nEnter first num to be divided: "; 
    cin >> x; 
    cout << "\nCool!! Now enter the 2nd number: \n"; 
    cin >> y; 
    cout << "\Exelent!! Enter the place upto which u wanna caculate: "; 
    cin >> z; 
    a = x/y; 
    cout << fixed << showpoint; 
    cout << setprecision(z); 
    cout << "Calculating......\n" << a << endl; 
    return 0; 
} 
+0

具有6個或更少有效小數位的所有數字都可以轉換爲IEEE 754浮點值,而不會降低精度。閱讀IEEE浮點類型。 –

+1

22/7絕對不是一個不合理的數字。 – molbdnilo

+0

哦,我的意思是PI @molbdnilo – ShivamProgramer

回答

3

浮點類型有一定的精度。在浮標(或雙打)上操作時,不會得到確切的結果。現在要獲得更好的精度,請使用double而不是float(有關更多詳細信息,請參見this post)。

你可以#include <limits>,除去從輸入得到精確的一步,你的代碼更改爲:

std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);

顯示具有最大精度爲你使用類型的結果。