c++ - c++中的函数错误
问题描述
我正在从一本名为“跳转到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 . . .
注意“结果是:”之前的错误
感谢任何帮助,谢谢
解决方案
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");
}
你可以在这里试试
随机数是由您造成的,cout << ask();
即使您没有返回任何东西。
正如 aschepler 指出的那样“确保启用并阅读编译器警告 - 应该有人说 ask() 尽管声明返回一个 int,但不会返回任何东西。”
推荐阅读
- go - Vscode (Mac OS) 在运行任务时有不同的 $PATH
- c++ - 将 OR-Tools 库添加到 Visual Studio
- swiftui - 如何在 SwiftUI 中显示长列表?
- java - 考虑到转义字符串,如何在 Java 中将字符串拆分为字符串
- android - window.print div 元素在 android chrome 上显示整个页面(在 win 10 chrome 上打印 div 部分)
- python - 根据选定的列过滤重复的行并与 Pandas 中的另一个数据框进行比较
- java - 如何在一个 Android 页面中保存文本文件并在另一个页面中打开它?
- python - 如何在 python 中将特定的 JSON 数据存储为列表
- python - 获取词干关键字的所有叶词
- postgresql - 具有几 GB 大小的数据集的 sparksql