如何使用主函数和来自 getData 函数的用户输入将值初始化为 int 变量 im



在 main 函数中,定义四个 int 类型的变量,命名为:第一、第二、第三和总计。

编写一个名为 getData 的函数,该函数要求用户输入三个整数,并将它们存储在主函数中的第一个、第二个和第三个变量中。

编写一个名为 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++中使用称为按引用传递的东西。默认情况下,将参数传递到函数中时,将复制该值。 但是按引用传递的作用是传递变量,而不是值。

例:

#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;。它会导致死亡、破坏和那些认为这是一件坏事的人的烦人答案。

附言 看到你所处的入门级别,我建议从Python开始。 看看吧! 学习起来容易多了。

最新更新