gpt4 book ai didi

c++ - c++中的函数错误

转载 作者:行者123 更新时间:2023-11-27 23:44:30 24 4
gpt4 key购买 nike

我正在学习 C++ 中的函数,这是一本名为“跳转到 C++”的书,有一个问题练习是创建一个计算器,我需要在单独的函数中进行算术运算,听起来很简单,我想我做到了 90 % 很好,程序给了我正确的答案,但有一些随机数。

代码是:

#include <iostream>

using namespace std;

int a, b;

int sum()
{

return a + b;

}

int subs()
{

return a - b;

}

int div()
{

return a / b;

}

int mult()
{

return a * b;

}

int ask()
{

cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;

}

int main()
{

int opcion;

cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;

if(opcion == 1)
{

cout << ask();

cout << "The result is: " <<sum() <<"\n\n";

} else if (opcion == 2)
{

cout << ask();

cout << "The result is: " << subs() <<"\n\n";

}else if (opcion == 3)
{

cout <<ask();

cout << "The result is: " << div() <<"\n\n";

}else if(opcion == 4)
{

cout << ask();

cout << "The result is: " << mult() <<"\n\n";

}else
{

cout << "Error.\n\n";

}

system("pause");

}

这是“错误/错误/任何”

1. Sum
2. Substraction
3. Division
4. Multiplication

Choose one option from above:

4
Give me the first number: 5

Give me the second number: 5
1878005856The result is: 25

Press any key to continue . . .

注意“The result is:”之前的错误

感谢任何帮助,谢谢

最佳答案

ask()不返回任何东西,所以它应该是一个空的。另外,你不需要做 cout << ask();ask()已经在里面打印了,它是空的(现在)所以不能打印。

修改后的代码,请查看前面带****的注释:

#include <iostream>

using namespace std;

int a, b;

int sum() {
return a + b;
}

int subs() {
return a - b;
}

int div() {
return a / b;
}

int mult() {
return a * b;
}

void ask() { // **** Changed to void here
cout << "Give me the first number: ";
cin >> a;
cout << "\nGive me the second number: ";
cin >> b;
}

int main() {
int opcion;

cout << "1. Sum \n2. Substraction \n3. Division \n4. Multiplication \n\nChoose one option from above: \n\n";
cin >> opcion;

if (opcion == 1) {
ask(); // **** Removed cout <<
cout << "The result is: " << sum() << "\n\n";
} else if (opcion == 2) {
ask(); // **** Removed cout <<
cout << "The result is: " << subs() << "\n\n";
} else if (opcion == 3) {
ask(); // **** Removed cout <<
cout << "The result is: " << div() << "\n\n";
} else if (opcion == 4) {
ask(); // **** Removed cout <<
cout << "The result is: " << mult() << "\n\n";
} else {
cout << "Error.\n\n";
}
system("pause");
}

可以试试here

随机数是你做cout << ask();造成的即使您没有返回任何东西。

正如 aschepler 指出的那样,“确保启用并阅读编译器警告 - 应该有人说 ask() 不返回任何东西,尽管声明返回一个 int。”

关于c++ - c++中的函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51736977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com