2013-07-25 65 views
-2

嘿傢伙想知道你是否可以幫助我下面的這段代碼。我的程序正在輸出一些奇怪的計算結果。C++算術運算符錯誤

#include <iostream> 

using namespace std; 

int main() 

{  

    int radius; 
    const double PI = 3.14159265; 
    float area; 
    float circumference; 


    cout << "Program to find the area and circumference of a circle\n\n\n"; 
    cout << "Please enter the radius: "; 
    radius = cin.get(); 

    area = PI * (radius * radius); 
    circumference = (2 * radius) * PI; 

    cout << "The area of your circle is " << area << ", the circumference of your circle is " << circumference <<"\n\n"; 
    system("PAUSE"); 

} 
+4

對於某些示例輸入,您希望輸出什麼,以及它實際輸出的是什麼? – BoBTFish

+0

什麼是'cin.get()'?爲什麼不使用流轉換'radius << cin;'? – wallyk

+0

你會得到什麼? – Engine

回答

5

這可能是因爲您正在使用:cin.get()

cin.get()只從輸入流中獲取一個字符。

這意味着在實踐中,如果你已在提示符下輸入1,該值將存儲爲一個字符和一個雙值(這是你真正想要的)。

而且,鑑於字符1等於49 in decimal notation ASCII表示,這意味着你的投入將解釋49 - 這是語法正確,但概念錯誤 - 因此你的結果。

很可能你會想要更多 - 你會希望你的所有輸入被正確存儲。因此,在這種情況下,最好使用cin如下:

cin >> radius; 

此外,中cin這樣使用的可能需要注意的是,它會自動跳過空白 - 這可以說是很好的根據其使用情況。相對於之前使用的cincin.get()),可能會導致比有意或無意間使用空格的值更多的問題。因此,在這種情況下,使用上面提出的流來解析輸入可能更好。

另一種選擇是使用標準C庫輸入以獲取輸入(如果你不喜歡處理流 - and there is debate regarding streams usage in C++ vs C-style IO):

http://www.cplusplus.com/reference/cstdio/scanf/

0

cin.get()返回一個字符,當將其轉換爲double,radius將得到錯誤的值。如

cin >> radius; 
0

istream::get功能提取字符而不是數量,應使用流轉換。對於大多數平臺,這意味着如果您輸入5,您將分配53radius as that is the [ASCII](http://www.asciitable.com/) value of'5'`。

使用正常的輸入操作>>閱讀次數,它會做正確的事情不管radius爲整數或浮點數變量:

cin >> radius; 
0

嘗試使用它之前打印您的半徑值,你就會知道

cin.get();作爲頁面說,

讀取一個字符並返回它(如果可用)。否則,返回 Traits :: eof()並設置failbit和eofbit。

您在控制檯上鍵入的數字被視爲字符並使用其ASCII值。

您需要使用cin>>radius這個

0

想盡計算後打印出來,你會得到什麼,也錯誤可能是原因:

radius = cin.get(); 
//Use cin or scanf instead 
cin >> radius; 
scanf("%d",&radius); 

或者因爲面積和迴旋的(浮動)和接收在線路值類型(雙):

area = PI * (radius * radius); 
circumference = (2 * radius) * PI; 

我建議任一鑄造,或使每一個變量類型浮子,如的sizeof(浮點)=的sizeof(int)的= 4字節。