The directions are: Design and code a program that asks the user how many numbers from which to determine an average. Then prompt the user for the integer values and sum them to a total. Display the sum of the numbers and the calculated average with appropriate accompanying text. The average should be shown with 1 decimal place. Repeat the process until the user enters zero (0) as the number of values to be averaged. You may use either a "while" loop or a "do…while" loop for the main program loop.
Use one function to read and sum the values and another function to display the sum and average. Use a "for" loop to read and sum the values.
The for loop doesn't seem to be executing, but I can't figure out why.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int sumNums(int amount, int, int, int);
void displaySum(int sum, int avg);
main()
{
int amount = 0;
cout <<"How many numbers do you wish to average? ";
cin >> amount;
int avg = 0, sum = 0;
while (amount != 0)
{
for (int lim = 0; lim == amount; lim++)
{
int number = 0;
cout <<"Enter a value"<< endl;
cin >> number;
sumNums(amount, number, sum, avg);
displaySum (sum, avg);
}
}
}
int sumNums (int amount, int number, int sum, int avg)
{
sum = sum + number;
avg = sum / amount;
return sum, avg;
}
void displaySum (int sum, int avg)
{
cout <<"The sum is "<< sum <<" and the average is "<< avg << endl;
}
for (int lim = 0; lim == amount; lim++)
Here you set lim to 0 and the code runs only if amount is not 0. In your for you execute only if lim equals amount which never happens.
Whatever your condition is, it must evaluate to true for every iteration that you want to do.
Most probably, you will want to execute until lim equals amount so that means that you want it to execute for every iteration where lim is lower than amount.
for(int lim = 0; i < amount; lim++)
for (int lim = 0; lim == amount; lim++) // so wrong...
change to
for (int lim = 0; lim < amount; lim++)
Related
I'm writing a program that prompts the user to enter integer numbers.
The program stops reading when user inputs 0.
It should output the max and min element among inputed numbers.
I must write it without using arrays.
Input: 1 2 3 4 5 0
Output: min=1 max=5
My code:
#include <iostream>
using namespace std;
int main()
{
int n,max,min;
min=0;
max=0;
do{
cin>>n;
if(n>max){
max=n;
}
if(n<min){
min=n;
}
}
while(n!=0);
cout<<max<<endl;
cout<<min;
}
The problem is that when I enter the integers from my example the output is min=0 max=5, instead of min=1 max=5.
How can I fix it?
You may want to input a starting value first, then loop:
int main()
{
int n, min, max;
cin >> n;
min = n;
max = n;
if (n != 0)
{
while (cin >> n)
{
if (n == 0) break;
if (n > max) max = n;
if (n < min) min = n;
}
}
std::cout << "min: " << min << ", max: " << max << "\n";
return 0;
}
In the code above, the first value is read and checked for 0. The program stops input if the value is zero.
The minimum and maximum are assigned the first value.
Then the loop starts.
See the below photo for reference:
I have a problem in finding the min and max number in .txt file.
The number is stored in a file as one number per line. The Programm should go through these numbers and find the biggest and smallest number.
Update: I solve this problem, but I face another issue due to the type of numbers.
Let say I have the following numbers:
0005.00
0005.23
52340.53
0000.01
0111.10
0001.00
2523.00
How can I get the right answers?
#include<fstream>
#include<cstdlib>
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter=0, number;
float sum = 0, average=0;
char file_name [20];
cout << "enter filename: ";
cin >> file_name;
ifstream input;
input.open(file_name);
if (! input)
{
cout << "Can't open file" << file_name;
//exit (0);
}
input >> number;
float min = number;
float max = number;
while (input>>number)
{
counter++;
sum=sum+number;
// Now, we can also check for Min/Max...
if (number > max) max = number;
if (number < min) min = number;
}
average=sum/counter;
cout<< fixed<<cout.precision(3);
cout<< "The average file in file test is was "<<average<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The largest number is: "<<max<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The smallest number is: "<<min<<endl;
input.close();
return 0;
}
When i run it, the min and max values are zero! Any help is appreciated.
Your first while loop will read to the end of file; thus, your second while loop won't actually read anything - you will already be at the file's end before it starts.
You should incorporate the code that is the 'body' of the second loop into the first one, and remove that 'redundant' second loop. You are also assigning the Min and Max variables the wrong way round:
while (input>>number)
{
counter++;
sum=sum+number;
// Now, we can also check for Min/Max...
if (number > Max)
Max = number;
if (number < Min)
Min = number;
}
average = sum / counter;
You should also give your Min and Max better initial values (unless you know there will be both positive and negative numbers in the data):
float number, sum = 0, average, Max = -FLT_MAX, Min = FLT_MAX;
Feel free to ask for further clarification and/or explanation.
This loop reads all numbers in the file:
while (input>>number)
{
counter++;
sum=sum+number;
}
After that loop, input is already at the end of the file and the next loop will not read any numbers.
Read the numbers once and do all processing in a single loop. Alternatively, store the numbers in a std::vector and then work on that.
Moreoever, you never modify Min and Max in your code. What this loop:
while (input>>number)
{
if (number>Max)
number=Max;
else
number=Min;
}
does instead is to clip the numbers such that any number bigger than 0 (Max) is set to 0 and any other number is set to 0 (Min).
You probably want something along the line of
double number;
input >> number;
double min = number;
double max = number;
while ( input >> number) {
if (number > max) max = number;
if (number < min) min = number;
}
I used the first number to initialize min and max. If you don't to that, 0 is no good initial value for min and max, but you can use std::numerical_limits<double>::min as initial value for max and std::numerial_limits<double>::max as initial value for min.
using namespace std;
#include<iostream>
class biker
{
public:
int initspeed, acc, speeding;
};
void input(int n, biker a[])
{
for (int i = 0; i < n; i++)
{
//cout<<"Enter the initspeed:"<<"\n";
std::cin >> a[i].initspeed;
//cout<<"Enter the acceleration:"<<"\n";
std::cin >> a[i].acc;
}
}
int main()
{
int n = 0, i = 0, t = 0, max_speed = 0, flag = 0, minimum = 0;
biker a[100];
std::cin >> t;
for (int k = 0; k < t; k++)
{
//cout<<"Enter no of bikers"<<"\n";
std::cin >> n;
//cout<<"enter the max track speed"<<"\n";
std::cin >> max_speed;
//cout<<"Enter the min niker speed"<<"\n";
std::cin >> minimum;
input(n, a);
int j = 1, x = 0;
while (flag < 500)
{
int sum = 0;
for (i = 0; i < n; i++)
{
int prod = 0;
prod = a[i].acc * j;
x = a[i].initspeed + prod;
// cout<<"VAL"<<x<<"\n";
if (x >= minimum)
{
//cout<<"It is greater than minimum";
sum = sum + a[i].initspeed + prod;
//cout<<sum<<"\n";
}
}
if (sum >= max_speed)
{
//cout<<"MAXIMUM ACHIEVED\n";
x = sum;
break;
}
j++;
flag++;
}
//cout<<x<<"\n";
std::cout << j;
}
return 0;
}
The above code is my solution to the bike racing problem in geeksforgeeks.
Summary:
A Bike race is to be organized. There will be N bikers. You are given initial Speed of the ith Biker by Hi and the Acceleration of ith biker as Ai KiloMeters per Hour.
The organizers want the safety of the bikers and the viewers.They monitor the Total Speed on the racing track after every Hour.
A biker whose Speed is 'L' or more, is considered a Fast Biker.
To Calculate the Total speed on the track- They Add the speed of each Fast biker ,at that Hour.
As soon as The total speed on the track is 'M' KiloMeters per Hour or more, The safety Alarm buzzes.
You need to tell what is the minimum number of Hours after which the safety alarm will buzz.
Input:
The first Line contains T- denoting the number of test cases.
The first line of each test case contains three space-separated integers N, M and L denoting the number of bikers and speed limit of the track respectively, and A fast Biker's Minimum Speed.
Each of next N lines contains two space-separated integers denoting Hi and Ai respectively.
Output:
For each test case-Output a single integer denoting the minimum number of Hours after which alarm buzzes.
Constraints:
1<=T<=100
1<=N<=1e5
1 ≤ M,L ≤ 1e10
1 ≤ Hi, Ai ≤ 1e9
My code runs properly on my computer and also on the ide .But when i click submit, it crashes returning Segmentation fault(SIGSEGV).
The array a can contain at most 100 bikers. The problem statement specifies that the number of bikers can be up to 10,000.
Overrunning the end of the array invokes Undefined Behaviour (UB) which is manifesting as a segfault on the judging system. Either the UB is manifesting differently on your development system or you have not tested it with a sufficiently large number of bikers.
I used Dev c++ 5.5.3 to write some programs. one of the programs is about getting some numbers (integer) until zero and then prints max, min , avg. In my computer everything is fine. in someone else computer, it does not show the right average and it shows very strange numbers 4.612521 e+8 and like this. I define a variable avg and calculate the value and then print it. The other one calculate the average directly when calling cout. can someone check This programs:
Program 1 which doesn't show the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
avg = (float) s/count ;
cout<<"Average: "<<avg<<endl; // NOTE NOTE NOTE NOTE
return 0;
}
Program 2 which shows the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
//avg = (float) s/count ;
cout<<"Average: "<<(float) s/count<<endl; //NOTE NOTE NOTE NOTE
return 0;
}
Both programs have undefined behaviour because s is not initialised and has not been assigned a value before you try to read from it for the first time:
int max , min , count = 0 , s;
[...]
s+=n;
All behaviour you have seen and the fact that it apparently "worked" on your computer and did "not work" on someone else's were more or less random occurrences.
Here's an easy fix:
int max , min , count = 0 , s = 0;
Note that your compiler should have warned you about the uninitialized variable. If not, then perhaps you should choose a higher warning level.
Also note that there are a lot of other flaws in your program, for example the use of using namespace std, that you declare multiple variables on the same line or that some of your variable names are not very descriptive.
I'm having a serious output problem with a program i made for my homework. Below is the code I'm using to calculate the mean and standard deviation for a group of numbers given by the user, until a flag value of -1 is reached. I am not allowed to use arrays. I am supposed to use a formula (for the std dev part) given by my professor which is ((sum (xi)^n) - ((sum xi) ^2/ n) /(n-1)) xi is x sub i, which is each input. I am using visual studio 2010 on a win7 x64 vm on my macbook pro (doubt this has anything to do, but just in case).
below is the code (followed by the screen cap of the error)
#include<iostream>
#include <cmath>
using namespace std;
int i;
int sum_unkown_vars();
double std_dev(int sum, int n);
/*double std_dev(int sum, int n)
{
double dev;
dev = sqrt(((pow(sum, 2.0)-(pow(sum, 2.0)/n)))/(n-1));
return dev;
}*/
int sum_unkown_vars()
{
i = 0;
int n;
int sum1 = 0;
int sum_sqd = 0;
double sdev;
cout<<"This part will sum variables given by user until flag value of -1"<<endl;
cout<<"\nNext Variable Please: ";
cin >> n;
while(n != -1)
{
sum_sqd = sum_sqd + n*n;
sum1 = sum1 + n;
i++;
cout<<"\nNext Variable Please: ";
cin >> n;
}
cout <<"\nNumber of variables is "<< i <<endl
<<"Sum of variables is "<< sum1 <<endl;
sdev = sqrt(((sum_sqd*1.0)-(1.0*pow(sum1, 2.0)/n))/(n*1.0-1.0));
cout <<"\nStandard Deviation is "<< sdev << endl;
return sum1;
}
int main()
{
int sum = 0;
int j;
double avg;
double std_dev1;
cout<<"This program will take integers given by the user,"
<<"\nsum them, then find average and standard deviation\n\n";
sum = sum_unkown_vars();
//cout <<"\nPlease enter number of integers previously given: ";
//cin >> j;
avg = sum / (i*1.0);
cout <<"\nAverage is: "<<avg<<endl;
//std_dev1 = std_dev(sum, i);
//cout <<"Standard Deviation is : "<< std_dev1 <<endl;
system("pause");
return 0;
}
Thanks in advance for any help received
The variable n in the formula
((sum (xi)^n) - ((sum xi) ^2/ n) /(n-1))
And the variable 'n' in the function
sum_unkown_vars()
are not the same. The n in the formula indicates the number of elements and this is defined by the variable 'i' in your program. Please correct this first.
Additionally number of variables should be either i+1 or you should increment i just after the initial reading.
I think there are still more errors in the code. e.g, you don't return the standard deviation from the function, you are using integer to return the standard deviation etc. Please debug the rest yourself with a debugger. Please make an expectation for the values and cross check it in the debugger.