简体   繁体   English

如何在不使用某种数组的情况下输入多个值

[英]How to enter multiple values without some sort of array

So basically I'm taking an intro tp programming class and we've been taught the basics (loops, if statements, variable types etc.) I'm solving a program where I have to ask the user to enter 6 different temperature values, and then print out the maximum, average and range of the 6 values. 因此,基本上,我正在上tp编程入门课程,并且已经接受了基本知识(循环,if语句,变量类型等)。我正在解决一个程序,在该程序中,我必须要求用户输入6个不同的温度值,然后打印出6个值的最大值,平均值和范围。

How and where should I store these 6 numbers? 我应该如何以及在哪里存储这6个数字?

cout<< "Enter 6 diff numbers" << endl;
float numbers;
cin >> numbers;

for ( .... i_++)

max = ;
min = ;


cout << .. << .... << endl;

//This should not help because float can only keep one number stored and not 6. How should I do this without using any sort of arrays, functions etc. ? //这应该没有帮助,因为float只能存储一个数字,而不能存储6。我应该如何在不使用任何数组,函数等的情况下执行此操作?

I was thinking using substrings and declaring it like a string or something?? 我正在考虑使用子字符串,并像字符串一样声明它?

Thanks for all your help. 感谢你的帮助。

I'm putting up the basic algorithm you can use without using arrays. 我提出了不使用数组就可以使用的基本算法。 Assuming everything in Kelvin. 假设一切在开尔文。

float max = 0; // Minimum Value Set for comparing with larger values
float min;
float sum = 0;
float avg = 0;
float tmp;
string number, alltheNumbers;
for( int i = 0; i < 6; i++ ){
   cin>>number;
   tmp = <float> number;
   if( tmp > max ){
      max = tmp;
   }
   sum += tmp;
   alltheNumbers += ',' + number; // Save all the numbers in comma seperated Strings
}
min = max;    // Maximum Found value set for finding minimum
std::string delimiter = ",";
size_t pos = 0;
while ((pos = alltheNumbers.find(delimiter)) != std::string::npos) {
    number = alltheNumbers.substr(0, pos); // Use the comma to retrieve all those numbers
    tmp = <float> number;
    if( tmp < min ){
      min = tmp;
    }
    alltheNumbers.erase(0, pos + delimiter.length());
}
avg = sum / 6;

So, You have the following variables with the required data. 因此,您具有以下具有所需数据的变量。

max <- will have the maximum value
min <- will have the minimum value
avg <- will have the average value.

This is one way to do it without arrays without spoiling the rest of your homework. 这是不使用数组而又不破坏其余作业的一种方法。

cout<< "Enter 6 different numbers" << endl;

float num1, num2, num3, num4, num5, num6, max, min, sum, avg;

cin >> num1 >> num2 >> num3 >> 
       num4 >> num5 >> num6;

Goodluck! 祝好运!

An improvement on @Zion's the first answer, I think initializing the min and max to the first digit should suffice. @Zion第一个答案的改进,我认为将最小值和最大值初始化为第一位数就足够了。 Before the for loop input number, then set max = number and min = number and then start for loop from i=1. 在for循环输入数字之前,然后设置max = number和min = number,然后从i = 1开始for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM