Closer
A kid has been working on an assignment in his math subject the entire night. His task is to find
the mean (arithmetic average) given a set of numbers and pinpoint which among the numbers
in the set is nearest to the mean. Although he knows exactly what to do, he is pressed against
time because his teacher gave more than 200 sets of values and it’s already time for school.
Your task is to help the kid locate the nearest number faster by creating a program to automate the
process.
INPUT FORMAT
The first line of input is D denoting the number of data sets, where d is 0 < D <= 100 . For each
data set there exists N number of values.
OUTPUT FORMAT
For each data set, get its mean and output the nearest number to the mean. Should there be a
value equal to the mean in the given set, ignore that value. If a nearest number does not exist,
output None. Should there be 2 or more nearest numbers, output the number with the smallest
value.
SAMPLE INPUT
5
1.0 2.0 3.0 4.0 5.0
2.0 4.0 6.2 8.9 10.1 12.5 14
2.0 2.0 2.0
1.0 1.0 1.0 0.5 -1.2 -2.0
20.0 30.0 40.0 50.0
SAMPLE OUTPUT
2.0
8.9
None
0.5
30.0
If you notice, the number of values in each line is not stated, the user can input as many values per data set/line of input. What is an efficient way to input an line of N values, where N is unknown? I tried using this code snippet but it didn't work:
1 2 3 4 5 6 7 8 9 10
cin >> n;
while ( i < n && n > 0 && n <= 100 ) {
j = 0;
double sum = 0;
while ( token != "\n" ) {
cin >> token;
num[j] = atof( token );
sum += num[j];
j++;
}
BTW, the code is incomplete, I didn't include the other parts of the outer while-loop.
I also thought of using getline() and then tokenize it but I think it's not efficient. Any reccomendations or corrections? How will I input as many values in each line? Is there such thing as "end-of-line" as there is "end-of-file"? Suggestions, please. Thanks a lot!
#include <iostream>
#include <sstream>
usingnamespace std;
int main()
{
string line;
getline(cin,line); // read a line of text
stringstream ss(line); // convert it to stringstream
float num,sum=0;
while( ss>>num )
sum+=num;
cout <<sum;
}