学习C ++ ...编译器意外地在某个点重复执行代码

时间:2015-03-18 03:11:00

标签: c++ c++11 stl

我今天开始学习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;
}

我将main函数的最后一部分注释掉以用于测试目的..当它们被取消注释时,编译器在main函数(getAge()getYearsFromNow())中执行两个调用,然后再做一遍,又一次,然后再执行剩下的代码..

我不明白..我在一个单独的函数中有最后一部分,只返回变量&#39; newAge&#39;但结果相同......

2 个答案:

答案 0 :(得分:1)

用户@ruakh指出,您正在调用函数getAge()getYearsFromNow()两次:

来到这里:

getAge();
getYearsFromNow();

再来一次:

newAge = getAge() + getYearsFromNow();

您要做的是第一次保存从函数返回的值,否则值将被丢失。您不需要再次调用这些函数。

因此,请将您的代码更改为以下内容:

int age = getAge();
int yearsFromNow = getYearsFromNow();
int newAge = age + yearsFromNow;
cout << endl << "In " << yearsFromNow << " years from now, you will be " << newAge;

现在发生的是getAge()的返回值将保存到变量age,而来自getYearsFromNow()的返回值将保存到变量{{1 }}。现在,您在计算和显示中使用这两个变量。

答案 1 :(得分:0)

int main()
{
    using std::cout;
    using std::endl;

    int age = getAge(); // call only once and assign to a variable
    int years = getYearsFromNow(); // call only once and assign to a variable

    int newAge;
    newAge = age + years;
    cout << endl << "In " << years << " years from now, you will be" << newAge; 

    return 0;
}