C++算术运算符错误

Dan*_*l M -2 c++ iostream user-input operators

嘿家伙们想知道你是否可以帮我解决下面这段代码.我的程序正在输出一些奇怪的计算.

#include <iostream>

using namespace std;

int main() 

{    

    int radius;
    const double PI = 3.14159265;
    float area;
    float circumference;


    cout << "Program to find the area and circumference of a circle\n\n\n";
    cout << "Please enter the radius: ";
    radius = cin.get();

    area = PI * (radius * radius);
    circumference = (2 * radius) * PI;

    cout << "The area of your circle is " << area << ", the circumference of your circle is "   << circumference <<"\n\n";
    system("PAUSE");

}
Run Code Online (Sandbox Code Playgroud)

jrd*_*rd1 5

这可能是因为你正在使用:cin.get().

cin.get() 只从输入流中获取一个字符.

这在实践中意味着如果你1在提示符下输入,那么该值将被存储为一个字符而不是一个double值(这是你真正想要的).

而且,考虑到的ASCII表示字符 1等于十进制49,这意味着你的输入将被解释49-这是语法正确的,但在概念上错了 -因此你的结果.

您可能不仅仅需要更多 - 您需要正确存储所有输入.因此,在这种情况下,最好使用cin如下:

cin >> radius;
Run Code Online (Sandbox Code Playgroud)

此外,这种使用的一个可能的警告cin是,它会自动跳过空白 - 根据其用途,这可以说是好的.相对于您之前使用的cin(cin.get())可能会导致更多问题,而不是故意或偶然使用空格.因此,在这种情况下,如上所述使用流来解析输入可能更好.

另一个选择是使用标准C库输入来获取输入(如果您不喜欢处理流 - 并且存在关于C++与C风格IO中的流使用的争论):

http://www.cplusplus.com/reference/cstdio/scanf/