【发布时间】:2015-03-18 03:10:59
【问题描述】:
我今天开始学习 C++,但遇到了一点小麻烦。 我正在尝试制作一个简单的程序来获取用户的年龄,要求他们输入一个他们想增加年龄的数字,然后输出这两个数字的总和。 在这里:
#include <iostream>
int getAge()
{
using std::cin;
using std::cout;
using std::endl;
cout << "Enter your age: ";
int age;
cin >> age;
cout << endl;
cout << "You are " << age << " years old.";
cout << endl;
return age;
}
int getYearsFromNow()
{
using std::cin;
using std::cout;
using std::endl;
cout << endl;
cout << "Enter how many years you want to increase yours age by: ";
int yearsFN;
cin >> yearsFN;
cout << endl << "Increasing your age by " << yearsFN << " years...";
return yearsFN;
}
int main()
{
using std::cout;
using std::endl;
getAge();
getYearsFromNow();
/*int newAge;
newAge = getAge() + getYearsFromNow();
cout << endl << "In " << getYearsFromNow() << " years from now, you will be
" << newAge; */
return 0;
}
出于测试目的,我将主函数的最后一部分注释掉了。当它们被取消注释时,编译器会执行主函数中的两个调用(getAge() 和 getYearsFromNow()),然后再执行一次,再一次,然后它才会执行其余的代码..
我不明白..我在一个单独的函数中的最后一部分只返回了变量“newAge”但结果是一样的..
【问题讨论】:
-
您知道每次调用
getAge()或getYearsFromNow()都会重新提示用户吗? (如果您是这么想的,程序不会“记住”并重用之前调用的结果。) -
那么我可以通过将两个调用分配给 main 中的一个变量来解决这个问题吗? @ruakh
-
试过了,成功了..谢谢@ruakh