using cout and averages errors or bugs - c++

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.

Related

need to output max and min (without array)

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.

How to fix output not adding together?

Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days.
The output earnings should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
Basically, the output displays the correct answer mathematically it just does not add them together. I am not sure on what to do to fix that issue.
//Declare Variables
int numDays = 1;
double money = 0.01;
double totalPay;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for (int i = 1; i <= numDays; i++)
{
cout<<"Pay = $"<<money;
money *=2;
}
//Exit stage right or left!
return 0;
Expected Output
Pay·=·$0.03
My Output
Pay·=·$0.01Pay·=·$0.02
//System Libraries
#include <iostream>//Input/Output Library
#include <iomanip>
using namespace std;
//User Libraries
//Global Constants, no Global Variables are allowed
//Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc...
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
//Declare Variables
int numDays = 1;
double totalPay;
double dayPay;
double money = 1;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for(int i = 1; i <= numDays; i++)
{
dayPay = money / 100;
totalPay += dayPay;
money *=2;
}
cout<<"Pay = $"<<fixed<<setprecision(2)<<totalPay;
//Exit stage right or left!
return 0;
}

Multiplication with functions in C++

I am new to functions and i am really trying to understand how they work, my teacher gave us a problem where by we were to pass a number to a function between the range of 1-12 and the function was then meant to do the times tales of that number so I asked the user to enter a number and if the number is less then 1 and greater then 12 exit, else pass the number to the function and then I used a for loop to do the multiplication for me (as far as I am aware) but nothing seems to happen? Νo doubt I am doing something really stupid, any help is much appreciated.
#include <iostream>
using namespace std;
int TimesTables (int num);
int main(int argc, const char * argv[]) {
int number;
cout << "enter a number to multiply by, with a range of 1-12: ";
cin >> number;
if (number < 1 && number > 12)
return EXIT_FAILURE;
else {
int tables = TimesTables(number);
cout << tables;
}
return 0;
}
int TimesTables (int num) {
for ( int i = 0; num <=12; i ++)
num = num * i;
return num;
}
Running i from 0 is going to set num to 0, and therefore any multiplication after that.
Your loop is also rather dubious. Why are you checking num <= 12 rather than i <= 12?
Shouldn't your loop take the form
for ( int i = 1; i <=12; i ++){
// Print num * i
cout << num * i;
}
// There's no need to return anything back to the caller
for ( int i = 0; num <=12; i ++)
num = num * i;
Here i starts from 0, so any multiplication you do afterwards doesn't affect the result (num). Moreover, you want to go from 1 to 12, so you should start from 0 and finish at 12 - 1, or start from 1 and finish at 12.
So change this:
for ( int i = 0; num <=12; i ++)
to this:
for ( int i = 1; i <=12; i ++)
since you want to stop when i reaches 12, not num, i is the counter of the for-loop!

Nearest value in an array

I am supposed write a function that is passed two parameters: a one-dimensional array of int values, and an integer value. The function finds the value in the array that is closest in value to the second parameter. My code works but not when I enter numbers 1-5 my output is 0. When I enter numbers above 5 then I start getting accurate results. I am not too sure why this is happening but here is my code so far:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 5;
int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;
for(int x = 0;x < MAX; x++)
{
if(value > abs(key - anArray[x]))
{
value = abs(key - anArray[x]);
num = anArray[x];
}
}
return num;
}
int main()
{
int A[MAX] = {3,7,12,8,10};
int search;
int nearest;
cout << "Enter a number to search: ";
cin >> search;
nearest = searchNearest(A,search);
cout << "The nearest number is: " << nearest << endl;
system("pause");
return 0;
}
In your original code, numbers 1-5 are closest to the first element of the array. Because of this, the code in the if statement is never executed, and when you return num, you return its initial value, which happens to be 0. To fix this, just initialize num differently:
int num = anArray[0]; // <-- used to be 0

Output problems with my standard deviation program

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.