c++ - 使用 UserInput ,c ++ 查找最大和最小数字
问题描述
我试图创建一个在主函数中调用的函数,以允许用户输入任意数量的数字,直到输入“0”。使用此函数给出输入的值的数量以及这些值的总和以及输入的最高和最低数字。
好的,所以假设输入的所有数字都是整数...... SmallestNum 的输出总是不正确......我花了几天时间试图解决这个问题,感觉我忽略或遗漏了一些东西......
我错过了什么?
int MaxMin_Int(int& sum,int& count,int& LargestNum,int& SmallestNum)
{
int num;
do{
cout<< "Enter Number (Press 0 to Exit): ";
cin>>num;
sum = sum + num;
count++; //incerement count...
if ( num > LargestNum) // Store Largest number in variable LargestNum
LargestNum = num;
else if ( num > SmallestNum && num < LargestNum )
SmallestNum = num; //Store Smallest number in SmallestNum varaible
}while(num != 0);
count--;
return sum,count,LargestNum,SmallestNum;
}
int main(){
//decleration of static variables
int sum = 0;
int count = 0;
int LargestNum = 0;
int SmallestNum = 1;
//Loop that breaks Once User Enters '0'
// Output the sum of numbers and number of numbers entered before program was executed.
//Sum_int(count,sum);
MaxMin_Int(sum,count,LargestNum,SmallestNum);
cout<<"\n\n"<<count<<" Values Were Entered"<<endl;
cout<<"With a sum of: "<<sum<<endl<<endl;
// Out put Highest And Lowest Numbers
cout<<"Largest Number Entered: "<< LargestNum <<endl;
cout<<"Smallest Number Entered: "<< SmallestNum <<endl;
return 0;
}
解决方案
有一些问题。在第一个输入 ( count == 0
) 之后,您必须设置LargestNum
和SmallestNum
。如果退出条件为 0,则忽略 0。使用条件 检测最小的数字if (num < SmallestNum)
。参数通过引用传递。不需要返回值。
void MaxMin_Int(int& sum, int& count, int& LargestNum, int& SmallestNum)
{
int num;
sum = count = LargestNum = SmallestNum = 0;
do {
cout << "Enter Number (Press 0 to Exit): ";
cin >> num;
if (num != 0)
{
if (count == 0)
LargestNum = SmallestNum = num;
else if (num > LargestNum)
LargestNum = num;
else if (num < SmallestNum)
SmallestNum = num;
sum += num;
count++;
}
} while (num != 0);
}
推荐阅读
- react-native - 无法在 iOS 模拟器上运行 expo 项目
- asynchronous - 如何在 Rust 中组合两个异步函数
- git - Visual Studio 代码中的 Git 表示即使没有更改,文件也会被修改
- vim - Vim 中的 :terminal 颜色方案与 Vim 或主机终端不同
- autodesk-forge - Forge Viewer 的性能
- pandas - 多个条件 np.where
- android - Flutter - 如何从相机获取实时输入并扫描任何物体?
- python - 我如何让这个代码计算单词而不是字母?
- javascript - 在画布Angular中放大和缩小图像的问题
- node.js - FileUpload Api using multer give 没有指定默认引擎,也没有提供扩展名