gpt4 book ai didi

c++ - 如何将用户输入作为参数传递给函数原型(prototype)?

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:13 24 4
gpt4 key购买 nike

#include <iostream>
#include <cmath>

using namespace std;

int nCount = 0, nX = 0;
double sum_total, nAverage;
// Function Prototypes

int Sum(int number); // Returns the sum of two ints
int Max(int i, int j); // Returns max of two ints
int Min(int i, int j); // Returns min of two ints
double Average(int nCount, int sum_total); // Returns the avg - (sum_total/count)

int main(){
cout << "How many numbers would you like to enter?" << endl;
cin >> nCount;
cout << "You would like to enter " << nCount << " numbers\n";

while (nX < nCount)
{
int a;
cout << "Please enter you numbers: "; // Pass this value into functions
cin >> a;
// Call Sum, Max, Min, and Average passing these two arguments
int Sum(a);
nX++;
}
cout << "The total is: " << sum_total << endl;
system("PAUSE");
return 0;
}

int Sum(int number)
{
sum_total = number + number;
return sum_total;
}

这是我正在处理的程序。我想要做的是让用户使用 cin 输入任意数量的整数,然后将该值传递给函数 int Sum 以将所有数字加在一起,然后显示它们的总和。 while 循环允许用户输入他们想要的数字数量,然后将该参数传递给下一个函数。但是,该程序将返回 0 作为总和。显示0的原因是什么?为了使这个程序运行,我需要做什么?

编辑

int Max(int number)
{
if (number > currentMax)
currentMax = number;
return currentMax;
}

//

int Min(int number)
{
if (currentMin < number)
currentMin = number;
return currentMin;
}

最佳答案

您的函数调用无效。你应该这样调用它:

Sum(a);

另外,因为 sum_total 是一个全局变量,所以您不需要从 Sum 返回一个值。

编辑

这里也是适当的 Sum() 定义:

void Sum(int number)
{
sum_total += number;
}

注意:不要忘记将 sum_total 初始化为 0。

关于c++ - 如何将用户输入作为参数传递给函数原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390657/

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