C++用户输入Age变量乘算转换月龄天数代码报错求解
错误根源
你的代码核心问题是变量计算顺序和输入顺序颠倒:
- 你在还没读取用户输入的
Age值时,就提前执行了days = 30 * month的计算,此时month和Age都是未初始化的随机值,触发了未定义行为,就是你看到的异常报错。 - 所有依赖
Age的计算逻辑,必须放在cin >> Age读取用户输入之后执行。
修正后的完整代码
#include <iostream> #include <string> using namespace std; int main() { string visitorname; cout << "Hello, welcome to Montgomery College! My name is Nao. May I have your name? \n"; getline(cin, visitorname); cout << "Nice to meet you " << visitorname << "\n"; cout << "Let me impress you with a small game.\n"; cout << "Give me the age of an important person or a pet to you.\n Please give me only a number:\n"; int Age; // 先读取用户输入的Age cin >> Age; // 再用有效Age值计算后续变量 int month = Age * 12; int days = 30 * month; cout << "You have entered " << Age << "\n"; cout << "If this is for a person, the age can be expressed as " << Age << " years "; cout << "or " << month << " months "; cout << "or " << days << " days (estimated by 30 days per month)\n"; return 0; }
关键修改说明
- 调整执行顺序:将
Age读取逻辑放在所有关联计算之前,保证month、days的计算都是基于用户输入的有效数值 - 去掉了未初始化变量的提前计算步骤,彻底避免未定义行为
- 补充了输出文本的空格和换行,优化显示效果,避免文本内容挤在一起
- 移除了没用的
<cmath>头文件引用,减少不必要的编译开销
内容的提问来源于stack exchange,提问作者briana pratt
相关产品推荐
相关产品推荐

