C Plus Plus无法正确计算

时间:2015-09-07 03:48:46

标签: c++

我制作了一个计算圆圈面积的程序。您可以选择输入直径或半径。选择其中一个后,输入值。然后它会告诉您输入的内容并给出答案。但答案是不正确的。例如,我输入'r'然后输入'3'它给我:

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;
}

3 个答案:

答案 0 :(得分:1)

因为你需要记住新事物:

切换案例和if / else语句非常相似,因此您不需要在同一任务中同时使用它们。

当程序运行时,用户输入值 r d ,该值将传递给 choice 变量。 switch case将自己的情况与选择值进行比较,如果两个值相等,它将运行该case代码块,如果不是,它将运行默认代码

现在在案例中,一旦获得半径,就要求半径

 result = number * number * M_PI; 

OR

result = pow(number,2.0) * M_PI;

cout&lt;&lt;&#;&#34; 2 * 3&#34 ;;和cout&lt;&lt;&lt; 2 * 3;

  

第一个示例将在屏幕上显示2 * 3.

     

第二个例子将2 * 3的结果显示在屏幕上    6 ,你计算的原因是因为周围没有引号

希望有帮助...

答案 1 :(得分:0)

result使用choise ???

的Shoulr计算

看起来你有一个错字。在

中替换choise woth number
result = choice*choice*M_PI;

并在

result = choice*M_PI;

在计算中使用choise实际上使用其ASCII码。这解释了您在result中获得的重要价值。

答案 2 :(得分:0)

result = choice*choice*M_PI;

这应该是

result = number * number * M_PI;

你也正在打印

* 2 * 3.14 =

应该是

^ 2 * 3.14 =