乘以双精度类型值会在输出中给出随机/垃圾答案

发布于 2025-01-02 17:59:35 字数 655 浏览 4 评论 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);
}

该程序要求输入姓名和年龄,并且应将姓名和年龄放在句子中,并将年龄以月为单位放在括号中。 输出给出类似: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜声 2025-01-09 17:59:35

您在初始化之前使用 age 进行乘法运算。您希望它能给您带来什么价值?

更改代码以首先获取年龄,然后进行乘法:

cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;

cout << "Hello " << name << " age " << age << " (" << months << " months)\n";

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:

cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;

cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
牵你的手,一向走下去 2025-01-09 17:59:35

的计算移至输入点年龄之后(age在原始代码中未初始化):

cout << "Enter your name and age: "; 
cin >> name >> age; 

months = age*12.0; 

cout << "Hello " << name << " age " << age << " (" << months << " months)\n"; 

Move the calculation of months to after the point age is entered (age was uninitialised in the original code):

cout << "Enter your name and age: "; 
cin >> name >> age; 

months = age*12.0; 

cout << "Hello " << name << " age " << age << " (" << months << " months)\n"; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文