gpt4 book ai didi

c++ - 我如何使用 main 函数和来自 getData 函数的用户输入将值初始化为 int 变量?

转载 作者:行者123 更新时间:2023-11-30 03:16:08 26 4
gpt4 key购买 nike

In the main function, define four variables of type int, named: first, second, third, and total.

Write a function named getData that asks the user to input three integers and stores them in the variables first, second, and third which are in the main function.

Write a function named computeTotal that computes and returns the total of three integers.

Write a function named printAll that prints all the values in the format shown in the following sample:

1 + 2 + 3 = 6

Call the other three functions from the main function.

Test it once, with the values 4, 5, and 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;
}

附言永远永远永远不要在你的代码中使用 using namespace std;。它会导致死亡、破坏和那些认为这是坏事的人的恼人回答。

附言看到你所处的入门级,我建议从 Python 开始。检查出!它更容易学习。

关于c++ - 我如何使用 main 函数和来自 getData 函数的用户输入将值初始化为 int 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554133/

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