在主函数中,定义四个int类型的变量,分别为:第一,第二,第三和总计。
编写一个名为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();
}
答案 0 :(得分:2)
使用您描述的代码布局基本上是不可能的。
但是!
在C ++中可以使用称为传递引用的东西。 默认情况下,将参数传递给函数时,将复制值。但是,按引用传递的功能是传递变量,而不是值。
示例:
#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;
}
P.S。永远不要在代码中使用using namespace std;
。
相信这是一件坏事的人会导致死亡,破坏和恼人的答案。
P.P.S。看到您的入门级别,我建议从Python开始。检查出!学习起来容易得多。