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.
How and where should I store these 6 numbers?
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. ?
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. Before the for loop input number, then set max = number and min = number and then start for loop from i=1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.