c++ - 如何使用 main 函数和 getData 函数的用户输入初始化 int 变量的值?
问题描述
在 main 函数中,定义了四个 int 类型的变量,命名为:first、second、third、total。
编写一个名为 getData 的函数,要求用户输入三个整数并将它们存储在主函数中的变量 first、second 和 third 中。
编写一个名为 computeTotal 的函数,计算并返回三个整数的总和。
编写一个名为 printAll 的函数,以以下示例中所示的格式打印所有值:
1 + 2 + 3 = 6
从主函数调用其他三个函数。
使用值 4、5 和 6 对其进行一次测试。
#include <iostream>
using namespace std;
int getData() {
cout << "Enter 3 Integer Values: ";
cin >> first >> second >> third;
return first, second, third;
}
int calcTotal() {
total = first + second + third;
return total;
}
int printTotal() {
cout << total;
}
int main() {
int first, second, third, total;
getData();
calcTotal();
printTotal();
}
解决方案
使用您描述的代码布局,这基本上是不可能的。
然而!
可以在 C++ 中使用称为 pass-by-reference 的东西。默认情况下,当您将参数传递给函数时,会复制该值。但是传递引用的作用是传递变量,而不是值。
例子:
#include <iostream>
void setToFive(int& x){// the ampersand signifies pass-by-reference
x = 5; // This change is preserved outside of the function because x is pass-by-reference
}
int main(){
int x = 200;
std::cout << "X before = "<<x<<std::endl;
setToFive(x);
std::cout << "X after = "<<x<<std::endl;
return 0;
}
因此,这种按引用传递意味着方法中变量的更改保存在方法之外。
所以你的代码看起来像这样:
#include <iostream>
void getData(int&first, int&second, int&third){
std::cout<<"Enter 3 Integer Values: ";
std::cin>>first>>second>>third;
}
int calcTotal(int first, int second, int third){//Pass as parameters, so the method knows what numbers to add
return first + second + third;
}//calcTotal returns the total
void printTotal(int total){//printTotal doesn't return anything! printTotal only prints stuff, it doesn't have a numeric result to give you
std::cout<<"Total: "<<total;
}
int main(){
int first,second,third;
getData(first,second,third);
int total=calcTotal(first,second,third);
printTotal(total);
return 0;
}
PS 永远不要using namespace std;
在你的代码中使用。它会导致认为这是一件坏事的人的死亡、破坏和烦人的答案。
PPS 看到您的入门级别,我建议您从 Python 开始。检查出!学习起来容易得多。
推荐阅读
- logback - 如何通过 App Engine Standard (Java) 在 Logback 上使用 jsonPayload?
- continuous-integration - wercker 中的链式管道(默认执行)不会产生结果
- c - 宏 - 生成 4 位查找表
- c++ - 调暗 vscode 中未使用的变量
- angular - 未捕获的错误:无法解析 HacksStorageService 的所有参数:([object Object],?)。在语法错误
- html - 为整个页面添加噪音
- reactjs - 找不到变量:React Native 的 react-native-material-bottom-navigation 中的选项卡
- c# - NHibernate如何将外键关系映射到多个属性
- python - 了解 Python 堆栈中的递归
- ios - 使用 Firebase 制作 iOS 应用原型