我做了一個計算一個圓的面積的程序。您可以選擇輸入直徑或半徑。選擇其中之一後,輸入值。然後它會告訴你你輸入的內容並給你答案。但答案不正確。例如,我輸入「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;
}
爲什麼你有一個**開關案例**和**如果陳述** – Lamar
@Lamar,我正在練習C++,因爲我是新手,所以我只是練習不同的東西。 –
'result = choice * choice * M_PI;'''choice''是'r',它是ASCII中的114。所以,你得到的結果非常有意義。你的意思可能是'result = number * number * M_PI;' – juanchopanza