用UserInput查找最大和最小的数字,c++
Finding Largest And Smallest Number With UserInput ,c++
im试图创建一个在主函数中调用的函数,以允许用户输入任意数量的数字,直到输入"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<<"nn"<<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;
}
您应该测试if ( num < SmallestNum)
。
此外,重新考虑SmallestNum
的初始值。如果输入是7 3 12
,会发生什么?所有数字都大于1
,因此即使用户的输入中没有1
,也不会将任何数字分配给SmallestNum
,并且输出将是1
。
存在一些问题。在第一次输入(count == 0
(之后,您必须设置LargestNum
和SmallestNum
。如果退出条件为0,则忽略0。最小的数目是用条件CCD_ 11来检测的。参数是通过引用传递的。不需要返回值。
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);
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组