【问题标题】:learning C++... compiler unexpectedly repeats execution of code at a certain point学习 C++... 编译器意外在某个点重复执行代码
【发布时间】: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

标签: c++ c++11 stl


【解决方案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() 的返回值将被保存到变量yearsFromNow。现在您在计算和显示中使用这两个变量。

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

    • 不是一个很有帮助的答案。您应该解释您的代码有何不同。
    • @Carcigenicate:我实际上同意。我到此为止,并注意到问题已根据 OP 中的 cmets 解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2016-12-24
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多