乘以双精度类型值会在输出中给出随机/垃圾答案
#include <iostream>
#include <string>
using namespace std;
int main() {
double age;
double months;
string name;
months = age*12.0;
cout << "Enter your name and age: ";
cin >> name >> age;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
return(0);
}
该程序要求输入姓名和年龄,并且应将姓名和年龄放在句子中,并将年龄以月为单位放在括号中。 输出给出类似: Hello Bob 年龄 20(1.82561e-313 个月),但应该是 Hello Bob 年龄 20(240 个月)。我没有使用 int,因为我希望能够输入年龄的非 int 值。 我尝试过 12 而不是 12.0,并尝试声明一个变量并执行 Months = Age*m 其中 m = 12.0 但结果是相同的。顺便说一句,无论年龄变量是什么,随机值都大致相同。为什么会发生这种情况?另外,这会是链接时错误还是运行时错误?
#include <iostream>
#include <string>
using namespace std;
int main() {
double age;
double months;
string name;
months = age*12.0;
cout << "Enter your name and age: ";
cin >> name >> age;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
return(0);
}
The program asks for name and age, and should out put the name and age in a sentence with the age in months in parentheses.
Output gives something like:
Hello Bob age 20 (1.82561e-313 months), but should be Hello Bob age 20 (240 months). I did not use int because I wanted to be able to input non int values for age.
I have tried 12 instead of 12.0 and tried declaring a variable and doing months = age*m where m = 12.0 but is result is the same. By the way, the random value is about the same regardless of what variable age is. Why is this happening? Also, would this be a link-time error or run-time error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在初始化之前使用
age
进行乘法运算。您希望它能给您带来什么价值?更改代码以首先获取年龄,然后进行乘法:
You're doing the multiplication using
age
before it's initialized. What value would you expect it to give you?Change your code to first get the age, and then do the multiplication:
将
月
的计算移至输入点年龄之后(age
在原始代码中未初始化):Move the calculation of
months
to after the point age is entered (age
was uninitialised in the original code):