C 加加计算不正确
C Plus Plus not calculating correctly
我做了一个程序来计算圆的面积。您可以选择输入直径或半径。选择其中一个后,输入值。然后它会告诉您输入的内容并为您提供答案。但答案是不正确的。例如,我输入"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 =
相关文章:
- 正弦级数方程计算不正确
- 计算幂级数的数学结果不正确
- 我的程序中的值计算不正确,即使支持数学是正确的
- 编译器在构造函数中计算的成员偏移量不正确
- 堆排序它不起作用或计算不正确
- 计算不正确
- C :不正确的文件大小计算Winapi
- 为什么此 stl 函数调用会导致不正确的布尔计算
- 平均计算不正确
- 斐波那契函数计算不正确
- 我正在尝试遍历 20x20 网格并计算产品,但总是得到不正确的结果。你能帮忙发现我的错误吗?
- 光线拾取方向计算不正确
- 计算后缀表达式.pop() 返回不正确的值来计算函数
- 为什么此代码不显示计算的正确答案,为什么它会无限循环?
- 为什么skb_transport_header计算不正确
- 计算delta不正确
- 使用cblas_dgemv()计算矩阵向量乘积的结果不正确
- 逻辑错误:平均质心计算不正确,无限执行,'entries '函数 - K 表示一组点的聚类,以C++为单位
- 字符/int相等计算不正确
- C 加加计算不正确