C 加加计算不正确

C Plus Plus not calculating correctly

本文关键字:不正确 计算      更新时间:2023-10-16

我做了一个程序来计算圆的面积。您可以选择输入直径或半径。选择其中一个后,输入值。然后它会告诉您输入的内容并为您提供答案。但答案是不正确的。例如,我输入"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;
}

既然你是新人,你需要记住几件事:

Switch Case 和 if/else 语句非常相似,因此您不需要在同一任务上同时使用它们。

当程序运行时,用户输入一个值r或d,该值被传递给选择变量。开关大小写将其自己的大小写与选择值进行比较,如果两个值相等,它将运行该大小写代码块,如果不是,它将运行默认代码

现在在箱子里,你要求半径,一旦你得到半径,

 result = number * number * M_PI; 

result = pow(number,2.0) * M_PI;

而且cout<<"2*3"之间也有很大的区别; 和 cout<<2*3;

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

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

希望有帮助...

result使用choise ???的 Shoulr 计算

看起来你有一个错别字。更换number choise

result = choice*choice*M_PI;

而在

result = choice*M_PI;

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

result = choice*choice*M_PI;

这应该是

result = number * number * M_PI;

你也在打印

* 2 * 3.14 =

应该是

^ 2 * 3.14 =