我想知道如何通过用户输入值在 C++ 中找到最大值和最小值,并且用户还设置了 for 循环的限制,例如:
编写一个 C++ 程序,最初从用户那里获取一个整数值作为循环的限制。这意味着循环将执行与用户输入相同的时间。然后循环将采用整数值作为用户的输入,直到达到循环限制。 您只需要使用一个变量,该变量将用于在循环内重复从用户那里获取输入。这意味着您不得为此目的使用数组或多个变量。之后,您的程序将计算输入值的总和、它们的平均值、最小值和最大值以及输入这些值的位置。
我写了但卡在最大值和最小值..这里是
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
using namespace std;
int main(){
int value;
int ivalue;
int sum=0;
int average;
int x,y;
cout << "Enter loop limit : "; cin >> value ;
cout<<endl;
cout<<endl;
for( x=0;x<=value-1;x++){
cout << "Enter "<<x+1<<" value : "; cin >> ivalue;
sum=sum+ivalue;
}
cout<<endl;
cout<<endl;
cout << "Sum of entered values : " <<sum <<endl;
cout << "Average of entered values : "<< sum/value<<endl;
}
最佳答案
您应该将最大值定义为可能的最低值:
int maximum = -INFINITY;
然后在每个值进行比较并在必要时设置新的最大值:
if (ivalue > maximum)
maxumum = ivalue;
至少你会使用相同类型的逻辑......
关于c++ - 通过用户输入在 C++ 中查找最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33994078/