I am trying to produce code with an output of:
Enter six fp numbers on a single line, separated by spaces: 1.5 2.1 3.8 4.2 5.7 6.1ENTER
Sum of 1.5 2.1 3.8 4.2 5.7 6.1 = 23.4\n
Average = 3.9\n
I started C a day ago so I literally don't know what I'm doing. This is the script I currently have. I know there are some punctuation errors.
#include <iostream>
using namespace std;
int main ()
{
int num1;
int num2;
int num3;
int num4;
int num6;
cout << "Enter six fp numbers on a single line, separated by spaces: ";
cin >> num1 >> num2 >> num3 >> num4 >> num5 >> num6 << endl;
How do I avoid issues listing numerical values and how do I insert a sum and average function? Any help would be appreciated thank you.
CodePudding user response:
I'll give you this much as a way to get started. This just computes the sum on the fly, rather than storing it in a vector, which is another great way t do this.
#include <iostream>
int main ()
{
std::cout << "Enter six fp numbers on a single line, separated by spaces: ";
double sum = 0.0;
double f;
for( int i = 0; i < 6; i )
{
std::cin >> f;
sum = f;
}
std::cout << "Sum is " << sum << "\n";
std::cout << "Average is " << (sum/6) << "\n";
}
Output:
Enter six fp numbers on a single line, separated by spaces: 1.2 3.4 5.6 7.8 9.1 2.3
Sum is 29.4
Average is 4.9
CodePudding user response:
What you did was just declare 5 integer variables, stored the numbers in them and simply calculated average there are some issues with that
1. The numbers you have stored are of the type float
2. There are simply better ways to do it but since you started with
C recently it is understandable
If you are not familiar with loops I suggest you read up on them but since we know the no of variables, a for loop would work fantastically here.
So what we can do is
#include <iostream>
int main ()
{
std::cout << "Enter six numbers on a single line, separated by spaces: ";
double sum = 0.0,buffer;
for( int i = 0; i < 6; i ) //For 6 iteration 0-5
{
std::cin >> biffer;
sum = sum buffer;
}
std::cout << "The sum of the Given nos is:- " << sum << "\n";
std::cout << "Average of the given nos is:- " << (sum/6) << "\n";
}
Output:
Enter six fp numbers on a single line, separated by spaces: 1.2 3.4 5.6 7.8
9.1 2.3
Sum of the Given nos is:- 29.4
Average of the given nos is:- 4.9
You can replace 6 with any number to make this program scalable
Good Luck