Why isn't my average working properly? C++ [duplicate] - c++

This question already has an answer here:
Integer division always zero [duplicate]
(1 answer)
Closed 2 years ago.
it seems that I'm stuck at c++ yet again. woohoo.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int amount = 0;
int inputNumber = 0;
int temp = 0;
int n = 0;
int lowest;
int highest;
double averages;
cout << "Welcome to simple calculator. Where you can use for average, highest amd lowest value.";
cout << "Please input all the number you plan to use to calculate. ";
cout << "Finish your input by enter any letter and then press on enter. " << endl;
while(cin >> inputNumber)
{
if (inputNumber < lowest) {
int (lowest = inputNumber);
}
else if(inputNumber > highest){
int (highest = inputNumber);
}
amount = amount += inputNumber;
n++;
}
double averages = amount / n;
cout << "Your lowest value is: " << lowest << endl;
cout << "Your highest value is: " << highest << endl;
cout << "Your average value is: " << averages << endl;
cout << "Amount is " << amount << endl;
cout << n << endl;
return 0;
}
but when I put in numbers it doesn't work properly. like
3
5
d
Your lowest value is: 3
Your Highest value is: 5
Your average value is: 4
2
-2
-3
a
Your lowest value is: -3
Your Highest value is: 0
Your average value is: -2
2
Idk why it do this and I'm still new to C++, I also have to code it in Linux and use G++
Thanks in advance if you could help me out.

try average = double(amount)/double(n);
Because average is double and n and amount

There are few errors in your code:
variable averages is defined twice.
Since for calculating amount you are doing int/int. which in result will yield int.
Thus your answer for -3 2 d will come wrong.
#include<iostream>
using namespace std;
int main()
{
int amount = 0;
int inputNumber = 0;
int temp = 0;
int n = 0;
int lowest=INT_MAX;
int highest=INT_MIN;
cout << "Welcome to simple calculator. Where you can use for average, highest amd lowest value.";
cout << "Please input all the number you plan to use to calculate. ";
cout << "Finish your input by enter any letter and then press on enter. " << endl;
while(cin >> inputNumber)
{
if (inputNumber < lowest) {
int (lowest = inputNumber);
}
else if(inputNumber > highest){
int (highest = inputNumber);
}
amount += inputNumber;
n++;
}
double averages = (double)amount / n;
cout << "Your lowest value is: " << lowest << endl;
cout << "Your highest value is: " << highest << endl;
cout << "Your average value is: " << averages << endl;
cout << "Amount is " << amount << endl;
cout << n << endl;
return 0;
}
This above code is correct code

Related

Extracting the minimum value from a file using a while loop c++

I am required to set the minimum value (minValue) equal to -1 in my declarations. How do I, using the || (or condition) within my while loop, extract a minimum value from a positive set of numbers considering that a negative value concludes the program? Also, the double average variable (average), is not calculating the intended value. For example, if the value is supposed to be 35.7789, it is returning 35.0000. I am also intending for the average value to return with no decimal point when unnecessary. For example, if the user enters a negative value first, the average value should be 0 as opposed to 0.0000. How do I manipulate the average variable in order to do so?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int intVal;
int sum = 0;
int maxValue = -1;
int minValue = -1;
double average = static_cast<double>(0);
int count = 0;
int evenCount = 0;
int oddCount = 0;
cout << endl << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
while(intVal >= 0)
{
if(intVal > maxValue)
maxValue = intVal;
if(intVal < minValue)
minValue = intVal;
count ++;
sum += intVal;
if(intVal > 0)
average = sum / count;
if(intVal % 2 == 0)
evenCount ++;
else
oddCount ++;
cout << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
}
cout << fixed << setprecision(4);
cout << "Values entered:" << setw(8) << right << count << endl;
cout << "Sum of numbers:" << setw(8) << right << sum << endl;
cout << " Average value:" << setw(8) << right << average << endl;
cout << " Maximum value:" << setw(8) << right << maxValue << endl;
cout << " Minimum value:" << setw(8) << right << minValue << endl;
cout << " Even numbers:" << setw(8) << right << evenCount << endl;
cout << " Odd numbers:" << setw(8) << right << oddCount << endl;
cout << endl;
}
I am required to set the minimum value (minValue) equal to -1 in my declarations.
With initialization to -1, all positive numbers will be greater than minValue.
You can set/initialize it with max value or first input value, or handling the special case in the loop:
if (minValue == -1 || intVal < minValue)
minValue = intVal;
Also, the double average variable (average), is not calculating the intended value.
Your average does integer arithmetic, you have to use floating point during the computation:
average = static_cast<double>(sum) / count;
the average value should be 0 as opposed to 0.0000
Remove the call to std::setprecision(4);

Unsure about a line of code that outputs a double or int

I am running into a bit of a confusion about one line in this code:
const int maxNum = 4;
int count = 1;
double num;
double total = 0;
double average;
while(count <= maxNum) {
cout << "please enter a number: " << endl;
cin >> num;
total = total + num;
cout << "The total is now: " << total << endl;
count++;
}
cout << "total of 4 digits is: " << total << endl;
//count--;
average = total/count;
cout << "the average of 4 digits is: " << average << "." << endl;
My question is in regards to count--;:
With count--; the average (double) has a decimal point.
But when I remove that line of code, the average is shown as only a integer.
What is the significance of this line?
After the while loop
while(count <= maxNum){
//...
count++;
}
count becomes equal to maxNum + 1 that is to 5 though only maxNum numbers were entered. So you need to decrease count before using it in calculating of the average. Though it would be better to use just maxNum instead of count.
It seems that diviting total by 5 you get an integer number.

How do I clear previous calculated data if user asks to repeat program? C++

Hello so I am a new programming student and I am practicing for my final. I know my program has flaws, but the major flaw is when the user repeats the program the new calculations are added onto the previous ones. How would I correct it?
My code is below for this task:
// Andranik Keshishyan, Quiz 2
#include <iostream>
#include <string>
#include <iomanip> //For setw and other formatting
#include <ctime> //For random number generation
using namespace std;
int main()
{
bool repeat = true; //Repeats program if true
srand(time(0)); //Random number generation
double amount_thrown, dice1, dice2, sum1, sum2, sum3, sum4, avg1, avg2, avg3; //Variables
char space = ' '; //Space for Formatting
cout <<"This program will roll 2 dice and calculate their sum and average depending on the amount of throws\n";
cout <<"The amount of throws cannot exceed 12\n";
while (repeat){ //Will repeat program if true.
cout <<"How many times would you like the dice thrown?: ";
cin >> amount_thrown;
cout << "\n";
if ((amount_thrown < 1 || amount_thrown > 12)||(!(cin>>amount_thrown))){ //Checks to see if user input is valid.
cout <<"This is an invalid input of dice throws.\n";
}
else //Continues program if valid.
{
cout <<"Throw" << setw(3) << space <<"Die 1" << setw(3) << space << "Die 2" << setw(3) << space << "Sum\n";
for(int x=1; x<=amount_thrown; x++){ //Loops program until amount of throws equals to user input
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
sum1 = dice1+dice2; //Calculates sum of dice1 + dice 2
sum2 += dice1; //Calculates sum of all dice 1 throws
sum3 += dice2; // Calcules sum of all dice 2 throws
sum4 += sum1; // Calculates summ of the sum
avg1 = sum2/2; // Calculates avg of sum of dice 1 throws
avg2 = sum3/2; // Calculates avg of sum of dice 2 throws
avg3 = sum4/2; // Calculates ave of sum of dice 1 + dice 2
cout << setw(2) << x << setw(7) << dice1 << setw(8) << dice2 << setw(9) << sum1 << endl;
}
cout << "-------------------------------------\n";
cout << "Sum" << setw(5) << space << sum2 << setw(6) << space << sum3 << setw(6) << space << sum4 << endl;
cout << "Avg" << setw(5) << space << avg1 << setw(5) << space << avg2 << setw(5) << space << avg3 << endl;
}
cout << "\nWould you like to roll the dice again?[y=repeat / anything else=stop]: ";
char answer;
cin >> answer;
cin.ignore(1000, '\n'); //Makes sure other inputs are ignored
answer=tolower(answer);
repeat = answer == 'y'; //Program will repeat if user inputs true char y.
}
cout << "Thank you, goodbye" << endl;
return 0;
}
You are not resetting your sum2, sum3, and sum4 variables back to 0 on each iteration of the while loop. That is why their values are cumulative over repeats of the program.
In fact, you are not even initializing them at all, so the total sum will be random garbage anyway.
You need to reset them to 0 on each while iteration, before entering the for loop.
The solution is to place all code in a function like void userInput(); then in int main() have a while loop which calls userInput(); then system("CLR"); which allows you to reset.

Highest and Lowest Integer C++

when I run this program is a "Run-Time Check Failure #2 stack around the variable 'numGrades' was corrupted" appears. Also the lowest grade doesn't output the correct answer. Any help would be greatly appreciated!
#include <iostream> // cin, cout
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = numGrades[0], lowest = numGrades[0], less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Sandro's Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, how many grades do I need to analyse this time? ";
cin >> numGrades[10];
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < numGrades[10]; count++)
{
cin >> numGrades[count];
sum += numGrades[10];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << numGrades << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}
Oh god, I don't even do c++ but I think one of my eyes bled a little.
Please review (or tell whoever coded this to review) how to create and assign values to them.
Then review simple data structures (like arrays) and loops.
One good way to start is to analyze the following WORKING code of your program:
Please mark as correct if it helps, and if you have any questions... Cheers!
#include <iostream>
#include <string>
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = 0, lowest = 0, less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Newbie Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, please enter 10 grades: "<<endl;
//THIS PART: loops ten times to input the grades
for (int count = 0; count < TEN_GRADES; count ++)
{
cout << "Grade number "<<count<<":";
cin >> numGrades[count];
}
//I get what you want to do here, but consider adding another exit condition here, what if the second grade is really 0 ?
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < TEN_GRADES; count++)
{
sum += numGrades[count];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << TEN_GRADES << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}

Maybe a syntax issue here?

Homework problem I am helping one of my mentees out with (check my history, I have previously asked help with Java in more advanced programs. This is something simple I can't help her figure out). We need to use a while loop to read in numbers, keep track of the count, and keep summing up the numbers entered. We keep getting an error in line 24. Even when I comment it out and run it, the programs doesn't do what it is supposed to do. Been forever since I've done a program in C++ and I need the help of you guys!
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
int count = 0;
float avg;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num; //
while (num != 999)
{
cout << "Number entered is" << num << endl;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num;
sum = sum + num;
count++;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
return 0;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
Change those +'s to <<'s.
cout << "Total numbers entered: " << count << endl;
cout << "Sum of numbers entered is " << sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" << avg << endl;
#include<iostream>
using namespace std;
int main()
{
int num,count;
float sum,average;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
count=0;
sum=0;
while (num!=999)
{
cout<<"Number entered is"<<num<<endl;
++count;
sum+=num;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
}
if (count==0) {
count=1;
}// if the first number you enter is 999 count should be 1
// , otherwise avg will be (sum/0 ),which doesn't make sense.
cout << "Total numbers entered: " <<count << endl;
cout << "Sum of numbers entered is " <<sum << endl;
average = sum/count;
cout << "Average of numbers entered:"<<average << endl;
// use << not + because "Total..." is string type and count is int type
system("pause");
return 0;
}
You should pay attention to the type of variable when you do something,which often can cause small errors.