微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我怎么知道非空函数的结果是什么而不执行它

如何解决我怎么知道非空函数的结果是什么而不执行它

在主体中 getwhattheywant 函数执行两次我想要的问题是 getwhattheywant 执行然后用户输入一个然后如果用户输入一个做求和操作但是我发生了什么它正在重新要求用户输入一个数字。

#include <iostream>
using namespace std;

double dothesum(int x,int y)
{
    int sum = x + y;
    return sum;
};
int getwhatheywant()
{
    int choice;
    cout << "1- for sum " << endl;
    cout << "2- for quit ";
    cin >> choice;
    return choice;
}
void the_sum()
{
    int x,y;
    cout << " enter the first number " << endl;

    cin >> x;
    cout << " enter the second number " << endl;
    cin >> y;

    cout << " the sum of the two number is " << dothesum(x,y) << endl;
}

int main()
{

    int;

    while (getwhatheywant() != 2) {
        if (getwhatheywant() == 1) {
            the_sum();
        }
    }

    return 0;
}

解决方法

更改您的 main():

int main()
{

    int whatTheyWant;

    while ( (whatTheyWant = getwhatheywant()) != 2) {
        if (whatTheyWant) == 1) {
            the_sum();
        }
    }

    return 0;
}

这会存储对 getwhattheywant() 的单个调用的值,因此您可以首先查看他们是否要求退出,如果没有,您可以查看他们可能还想要什么。现在,我的写法略有不同:

bool working = true;
while(working) {
   int choice = getWhatTheyWant();
   switch(choice) {
       case 1: the_sum(); break;
       case 2: working = false; break;
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。