2015-09-07 44 views
-5

我做了一個計算一個圓的面積的程序。您可以選擇輸入直徑或半徑。選擇其中之一後,輸入值。然後它會告訴你你輸入的內容並給你答案。但答案不正確。例如,我輸入「r」,然後輸入它給我的'3':C Plus Plus計算不正確

This is a calculator that calculates the area of a circle. 
To get started, type 'd' (no quotes or caps) to enter a diamater. 
Type 'r' (no quotes or caps) to enter a radius. 
r 
You chose radius, now please enter a number. 
3 
3 * 2 * 3.14 = 40828.1 

它看起來不正確,如你所見。也許C++的Pi變量已經過時了?

#include <iostream> 
#include <math.h> // Importing math.h so I can use the M_PI variable. 
using namespace std; 

int main() { 
char choice; 
float result = 0.0; // Set to zero to init and stop the IDE from complaining. 
float number = 0.0; 

cout << "This is a calculator that calculates the area of a circle." << endl; 
cout << "To get started, type 'd' (no quotes or caps) to enter a diamater." << endl; 
cout << "Type 'r' (no quotes or caps) to enter a radius." << endl; 

cin >> choice; 

choice = tolower(choice); // Making it lower case so it's easier for compiler to recoginize. 


switch (choice) { 
case 'r': 
     cout << "You chose radius, now please enter a number." << endl; 
     cin >> number; 
     result = choice*choice*M_PI; 
break; 

case 'd': 
     cout << "You chose radius, now please enter a number." << endl; 
     cin >> number; 
     result = choice*M_PI; 
break; 

default: 
     cout << "You entered an invalid character. Please only enter 'r' or 'd' (no quotes or caps)" << endl; 
break; 
} 

if (choice == 'r') 
{ 
    cout << number << " * 2 * 3.14 = " << result << endl; 
} 
else if (choice == 'd') { 
    cout << number << " * 3.14 = " << result << endl; 
} 
else { 
    cout << "Nothing here cause you didn't do simple stuff correctly..." << endl; 
} 
return 0; 
} 
+0

爲什麼你有一個**開關案例**和**如果陳述** – Lamar

+0

@Lamar,我正在練習C++,因爲我是新手,所以我只是練習不同的東西。 –

+2

'result = choice * choice * M_PI;'''choice''是'r',它是ASCII中的114。所以,你得到的結果非常有意義。你的意思可能是'result = number * number * M_PI;' – juanchopanza

回答

1

因爲你是你需要記住新的幾件事情:

switch case和if/else語句非常相似,因此您不需要同時在同一個任務上使用它們。

當程序運行時,用戶輸入一個值要麼řd,該值獲得傳遞給選擇變量。開關櫃比較自己的情況與選擇值,如果兩個值相等,它將運行該情況代碼塊,如果它們不是,它將運行默認代碼

現在的情況裏面,你所要求的半徑,一旦你的半徑,

result = number * number * M_PI; 

OR

result = pow(number,2.0) * M_PI; 

而且也有COUT < < 之間有很大的區別「 2 * 3" ;和cout < < 2 * 3;

第一個示例將在屏幕中顯示2 * 3。

第二個例子將顯示2 * 3的結果到屏幕 ,你把它計算的原因,因爲沒有它周圍

希望引號幫助...

0

首爾計算result使用choise ???

看起來像你有一個錯字。在

result = choice*choice*M_PI; 

而在

result = choice*M_PI; 

在計算使用choise更換choise woth number實際使用的ASCII碼。這解釋了您在result中獲得的重要價值。

0
result = choice*choice*M_PI; 

這應該是

result = number * number * M_PI; 

也正在打印

* 2 * 3.14 = 

應該

^ 2 * 3.14 =