通过用户输入在 C++ 中查找最大值和最小值 [英] Finding Maximum and Minimum values in c++ by user input

查看:142
本文介绍了通过用户输入在 C++ 中查找最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何通过用户输入值找到 C++ 中的最大值和最小值,并且用户还为循环设置了限制,例如:

i want to know how can i find the maximum and minimum value in c++ by user input value and and user also put the limit for for loop , for example :

编写一个 C++ 程序,它最初从用户那里获取一个整数值作为循环的限制.这意味着循环将执行与用户输入相同的次数.然后循环将采用整数值作为用户的输入,直到达到循环限制.您只需要使用一个变量,该变量将用于在循环内重复接收用户的输入.这意味着您不能为此使用数组或多个变量.之后,您的程序将计算输入值的总和、它们的平均值、最小值和最大值以及输入这些值的位置.

Write a c++ program that initially takes an integer value from the user as the loop’s limit. It means that the loop will execute the same times as the input from the user. The loop will then take integer values as input from the user until it reaches loop limit. You are required to use only one variable which will be used to take input repeatedly from the user inside the loop. It means you are not allowed to use the array or multiple variables for this purpose. After that your program will calculate sum of entered values, their average, minimum and maximum values along with position on which these values were entered.

我写了但坚持最大值和最小值..这里是

i wrote but stuck on maximum and minimum.. here is

#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;

 }

推荐答案

您应该将最大值定义为可能的最小值:

you should define the maximum as the lowest possible value:

int maximum = -INFINITY;

然后在每个值比较并在必要时设置新的最大值:

then at each value compare and set new maximum if necessary:

if (ivalue > maximum)
    maxumum = ivalue;

至少你会使用相同类型的逻辑......

for minimum you would use the same kind of logic...

这篇关于通过用户输入在 C++ 中查找最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆