C++: The average output of my program doesn't show properly - c++

I've already had searched around the internet for some answers, but I can't seem to find the answer. I guess this program would be easier if I use for loop but my professor ordered us to use the while loop statement.
#include <iostream>
using namespace std;
int main()
{
float value[10];
float average;
float min;
float max;
int index1 = 0, index2 = 0, index3 = 0, index4 = 0, sum;
while (index1 < 10)
{
cout << "Enter a value : ";
cin >> value[index1];
index1++;
}
while (index2 < 10)
{
sum += value[index2];
index2++;
}
max = value[index3];
while (index3 < 10)
{
if (max < value[index3])
{
max = value[index3];
}
index3++;
}
min = value[index4];
while (index4 < 10)
{
if (min > value[index4])
{
min = value[index4];
}
index4++;
}
average = sum / 10;
cout << "The average is : " << average << "\n";
cout << "The largest value is : " << max << "\n";
cout << "The smallest value is : " << min << "\n";
}
Here's how it looks when I run it.
Enter a value : 98
Enter a value : 45
Enter a value : 32
Enter a value : 21
Enter a value : 67
Enter a value : 54
Enter a value : 74
Enter a value : 25
Enter a value : 98
Enter a value : 33
The average is : -2.00668e+008
The largest value is : 98
The smallest value is : 21

You are seeing the result of integer division, and uninitialized variables. Divide by 10.0 rather than 10 so that compiler coerces both values to a floating point number. Also assign 0 to sum when you are declaring it.
I am assuming there are other warnings too in your program since you are implicitly assigning floating point values to an integer too.

Move variables outside of the main function globally and there is no need to initialize them. Also, you can do calculations using only one loop.
#include <iostream>
using namespace std;
float value[10], average, min, max, sum;
int index;
int main()
{
while (index < 10)
{
cout << "Enter a value : ";
cin >> value[index];
if (value[index] > max) max = value[index];
if (value[index] < min) min = value[index];
sum += value[index];
index++;
}
average = sum / 10.0;
cout << "The average is : " << average << "\n";
cout << "The largest value is : " << max << "\n";
cout << "The smallest value is : " << min << "\n";
}

sum should be equal to zero at point of declaring otherwise it will have garbage value.
int index1 = 0, index2 = 0, index3 = 0, index4 = 0, sum = 0;

Related

Accessing the value of the last iteration from inside the loop

I know this might be just an if statement that i don't know where to place but i am having difficulties understanding how to proceed.
#include <time.h>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
float a;
float sum;
float tA = 5050 ;
int b [5] = {5, 10, 15, 30, 100};
double bin;
double divident;
cout<<"Random numbers generated between 0 and 1:"<<endl;
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 5; i++)
{
a = (float) rand()/RAND_MAX;
sum += a;
cout << a << "\t Total: " << sum << "\t Bin: " << a* divident << endl;
}
cout << "Total of Random Numbers: " << sum << endl;
divident = tA/sum;
cout <<"Divident: "<< divident << endl;
cout <<"Last a: "<< a << endl;
return 0;
}
OUTPUT:
Random numbers generated between 0 and 1:
0.228659 Total: 0.228659 Bin: 0
0.337218 Total: 0.565877 Bin: 0
0.955376 Total: 1.52125 Bin: 0
0.356451 Total: 1.8777 Bin: 0
0.7963 Total: 2.674 Bin: 0
Total of Random Numbers: 2.674
Divident: 1888.55
Last a: 0.7963
The dividend should be a variable (tA)/the sum of all 5 random generated numbers (2.674) and every random value of 'a' be multiplied by it on every row (inside bin column). But I do not know exactly how to access it since in the code it is the last iteration of 'sum'
as you can see my next step is to place all five values into a designated array bin *int b[5](labeled 5, 10, 15, 30, 100). and eventually multiply the expected frequency in every bin with the bin label(5,10,15.. 1000) I'm thinking std map or something similar, so any advanced std solutions or pointers (sic) on how to proceed further would greatly be appreciated.
You can only compute divident after the end of the loop, but you want to use it starting with the first iteration: that is not possible using one single loop. You should use two loops, first one to compute sum and divident, and second one to display the values:
float sum = 0;
...
double arr[5];
for (int i = 0; i < 5; i++)
{
a = (float)rand() / RAND_MAX;
sum += a;
arr[i] = a;
}
divident = tA / sum;
for (int i = 0; i < 5; i++)
{
a = arr[i];
cout << a << "\t Total: " << sum << "\t Bin: " << a * divident << endl;
}

Beginner to C++ - How to sum up only positive or only negative integers the user inputs and how to calculate the avg

Total Noob here, I am having a hard time with an assignment. I am taking a beginner course in C++ and have to figure out how to calculate the sum of negative integers and their avg. Sum of positive integers and the avg. And the sum of all numbers and the avg. I have gotten the last part already but how do I calculate the sum of negative integers and avg, and positive integers and avg using a while loop?
I provided my code below.
#include <iostream>
using namespace std;
#include <iomanip>
int main(int argc, const char * argv[]) {
int x;
double avg = 0.0;
int count = 0;
int sum = 0;
// ask users for input
cout << ("Welcome to the greatest calculator!\n");
cout << ("Please enter 10 integers seperated by spaces \n");
do {
std::cin >> x;
sum = sum + x;
count = count + 1;
}
while (count < 10);
// calculate average
avg = sum/10.0;
// output average
cout << fixed;
cout << "For all 10 numbers the sum is " << sum << "." "The average is " << setprecision (2) << sum/10.0 <<".\n";
return 0;
}
The output should look something like this.
Please enter 10 integers separated by spaces:
1 -1 45 17 28 -2 0 9 -14 11
Upon our intelligent calculations, here is the result:
+ There are 7 positive numbers, sum = 111.00 and average = 15.86
+ There are 3 negative numbers, sum = -17.00 and average = -5.67
+ For all 10 numbers, sum = 94.00 and average = 9.40 */
Use two variable int negativeVar=0 , PositiveVar=0 . In the loop try a condition if(GivenNumber<0) to detect the given number is negative or positive. Then add all positive and negative value separately and make avarage.
(Sorry for bad english)
You can do like this (notice comments):
#include <iostream>
int main(void) {
// Declaration and initialization of the required variables
float cPositive = 0.0f;
float cNegative = 0.0f;
int it = 0;
std::cout << "Enter 10 numbers (floating point assignable): \n";
// Looping till 10 iterations
do {
float temp;
std::cin >> temp;
// If the number is greater than zero, i.e. (+ve) then cPositive sums up
// otherwise, cNegative
if (temp > 0) cPositive += temp;
else if (temp <= 0.0f) cNegative -= temp;
} while (++it < 10); // Increment and comparison together
// Final results
std::cout \
<< "Sum of positive: " << cPositive << std::endl
<< "Sum of negative: -" << cNegative << std::endl;
return 0;
}
A simple test case:
Enter 10 numbers (floating point assignable):
10.5
-1.5
2.2
5.5
-3.8
-99.3
10
4.5
-1.0
0
Sum of positive: 32.7
Sum of negative: -105.6
Moreover, if you want to see average, then declare two variables, pos and neg where both are initially zero. After that, when a positive number or negative number occurs, just increment pos or neg and divide with them by cPositive or cNegative respectively.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// lets declare some variable first.
int positiveSum =0; //this will hold sum of positive nums
int negativeSum =0; // this will hold sum of negative nums
int totalSum =0; // this will hold sum of all the nums
int number=0; // user input for number
for (int i = 1; i <=10; i++) // loop from 1 to 10 times
{
cout << " Enter a number: ";
cin >> number;
// now check if number is positive or negative
if (number >=0)
{
positiveSum += number; // adds this number to positiveSum
}
else if (number < 0)
{
negativeSum += number; // adds this number to negativeSum
}
}
// So finally add the positiveSum and negativeSum to get the totalSum
totalSum = positiveSum + negativeSum;
cout << endl;
cout << " Total of Positive numbers is: " << positiveSum << endl;
cout << " Total of Negative numbers is: " << negativeSum << endl;
cout << " Total of all numbers is: " << totalSum << endl;
return 0;
}
The code below produces the following output:
$ ./main
The (sum, avg) of negative integers = (-15, -5)
The (sum, avg) of positive integers = (6, 2)
The (sum, avg) of all numbers = (-9, -1.5)
Please read the comments because they are in fact the detailed answer.
#include <array>
#include <iostream>
int main()
{
// For convenience, keep the numbers in an std::array. std::vector is
// equally convenient.
std::array<int, 6> integers { 1, -4, 2, -5, 3, -6 };
// Define variables that store the sums and the counts.
int positiveSum = 0;
int positiveCnt = 0;
int negativeSum = 0;
int negativeCnt = 0;
// Iterate over the numbers taking one of them at a time.
int i = 0;
while (i < integers.size())
{
int number = integers[i];
// Is the number positive?...
if (number >= 0)
{
// ... it is - add it to the positive sum and increment the count.
positiveSum += number;
++positiveCnt;
}
// The number is not positive, so it must be negative...
else
{
// ... add it to the negative sum and increment the count.
negativeSum += number;
++negativeCnt;
}
// Get ready for the next number.
++i;
}
// Time to print out the results.
// Note that before we calculate the average, we have to cast at least one
// of the terms of the division to floating point type. Otherwise the
// division will be done with integers where the result is also an integer
// (e.g. 3 / 2 -> 1).
// Only affter the casting you will be getting expected answers
// (e.g. double(3) / 2 -> 1.5).
std::cout <<
"The (sum, avg) of negative integers = (" <<
negativeSum << ", " <<
double(negativeSum) / negativeCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of positive integers = (" <<
positiveSum << ", " <<
double(positiveSum) / positiveCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of all numbers = (" <<
negativeSum + positiveSum << ", " <<
double(negativeSum + positiveSum) / (negativeCnt + positiveCnt) << ")" << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
char op;
float num1,num2;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
//If the operator is other than +,-,*,/, error message is shown.
cout << "Error! operator is not correct";
break;
}
return 0;
}

How can I find the minimum value correctly that enter by user?

Most of the code seems to be okay need help with the part to find the minimum. What condition do I have to write in order to find the minimum number enter by user and exclude the zero as minimum number?
#include<iostream>//header
#include <string>
using namespace std;
int main() {
int n , sentinel = 0, max = 0, min, count = 0, sum = 0;
double avg;
cout << "Enter a series of number terminated by 0:" << endl;//prompt user to input a series of number
do {
cin >> n;//read the input
for (int i = 0; i < n; i++) {
if (n>max)
max = n;
}
for (int i = 0; i < n; i++) {
if (n<min)
min = n;
}
sum = sum + n;
count++;
} while (n!= sentinel);
count--;
avg = sum / count;
cout << "You have enter " << count << " integers" << endl;//display how may input user enter
cout << "Average is " << avg << endl;//display average
cout << "Max is " << max << endl;//display maximum number
cout << "Min is " << min << endl;//display minimum number
system("pause");
return 0;
}
You can start with the maximum possible value for your int min; and the minimum possible value for your int max;:
int min = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();
Then whatever you enter for the min must be smaller than its initial value and whatever you enter for the max must be larger than its initial value.

Chapter 4 Stroustrup Drill. A challenging step (at least for me!)

I'm working through Stroustrups's "Programming Principles and Practice using C++" and got stuck in one exercise.
Here are the indications :
1) Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.
2)Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the larger value.
3)Augment the program so that it writes the line the numbers are equal (only) if they are equal.
4)Change the program so that it uses doubles instead of ints.
5)Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100.
6) Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have seen so far. Each time through the loop write out the value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.
This is the code I have so far:
int main(){
double number1 = 0;
double number2 = 0;
double maximum = 0;
double minimum = 0;
cout << " Keep entering numbers. If you want to exit the program press alt + z" << endl;
while (cin >> number1 && cin >> number2) {
if (number1 == '#' || number2 == '#') {
break;
}
else if (number1 < number2){
cout << "The smaller value is " << number1 << '.' << endl;
cout << "The larger value is " << number2 << '.' << endl;
maximum = number2;
minimum = number1;
if (number2 - number1 < 0.01) {
cout << "The numbers are almost equal";
}
}
else if ( number1 > number2) {
cout << "The smaller value is " << number2 << '.' << endl;
cout << "The larger value is " << number1 << '.' << endl;
maximum = number1;
minimum = number2;
if (number1 - number2 < 0.01) {
cout << "The numbers are almost equal";
}
}
else {
cout << "Both numbers are the same." << endl;
}
}
Can somebody help me modify this to find the largest, smallest number?
I've read about it and found a sorted vector solution but I can't seem to apply it to my problem.
Much appreciated :)
If you want to keep a running count of the maximum and minimum and not make structural changes to your existing program,
You'll need to '#include < algorithm >' unless you want to roll your own min and max functions.
Instead of:
maximum = number1;
minimum = number2;
Use this:
maximum = (maximum < max(number1, number2)) ? max(number1, number2) : maximum;
minimum = (minimum > min(number1, number2)) ? min(number1, number2) : minimum;
For Exercise 6, you don’t have to use std::vector. You can keep track the largest and smallest values in single variables called minn and maxn as shown in the following code snippet:
int
main()
{
std::string quit("|");
int i = 0;
std::string s;
double n;
std::vector < double >v = { 0.0, 0.0 };
double maxn = std::numeric_limits < double >::lowest();
double minn = std::numeric_limits < double >::max();
std::vector < double >in_meters;
while (std::cin >> s) {
if (quit.compare(s) == 0)
break;
if (reject(s))
continue;
n = str2meters(s);
std::cout << n << " ";
in_meters.push_back(n);
if (maxn < n) {
std::cout << "the largest so far" << std::endl;
maxn = n;
}
if (minn > n) {
std::cout << "the smallest so far" << std::endl;
minn = n;
}
v[i] = n;
if (i == 1) {
std::sort(v.begin(), v.end());
prn(v);
}
i = (i + 1) % 2;
}
prng(in_meters);
return 0;
}
I have used std::vector for Exercises 2 and 5:
void
prn(std::vector < double > &v)
{
const double one_percent = 1.0 / 100.0;
std::cout << "the smaller value is: " << v[0] << std::endl;
std::cout << "the larger value is: " << v[1] << std::endl;
if ((v[1] - v[0]) < one_percent)
std::cout << "are almost equal" << std::endl;
}
and Exercises 9-11, too:
void
prng(std::vector < double > v)
{
std::sort(v.begin(), v.end());
for (auto k : v)
std::cout << k << " " ;
std::cout << std::endl;
double sum = std::accumulate(v.begin(), v.end(), 0.0);
std::cout << "number of values " << v.size() << std::endl;
std::cout << "sum of values " << sum << std::endl;
}
You're making it complicated, start with this using 'std_lib_facilities'
#include "..\..\std_lib_facilities.h"
int main() {
cout << "type in two integers or a '|' to terminate the program:\n";
int x1 = 0;
int x2 = 0;
while (cin >> x1 >> x2)
{
cout << x1 << ", " << x2 << "\n";
}
keep_window_open("x");
}

Function not returning the highest and lowest values entered into the array

This function is not accurately returning the highest and lowest values entered into the array. I'm not sure what I code I entered for the program to do this. This program needs to return the average of all of the elements entered into the array (the average part works fine) as well as find the highest and lowest values among all of the values entered into the array. Please help!
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average(int);
void highest(int);
void lowest(int);
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
if (days > 50)
{
cout << "You may only enter temperatures for 50 days." << endl;
return 0;
}
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
return averagetemp;
}
void highest(int days)
{
int count;
int highest;
highest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] > highest)
highest = temperatures[count];
cout << "The highest temperature is: " << highest << endl;
}
}
void lowest(int days)
{
int count;
int lowest;
lowest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] < lowest)
lowest = temperatures[count];
cout << "The lowest temperature is: " << lowest << endl;
}
}
This function
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
is already wrong because element temperatures[0] will not be uninitialized. You have to write
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i-1];
temptotal += temperatures[i-1];
//...
Or
float average(int days)
{
for (int i = 0; i < days; i++)
{
cout << "Enter the temperature for day number " << i + 1 << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
Functions highest and lowest are also wrong. For example array temperatures has no element with index 50. Moreover the user can enter number of days less than 50. So this statement
highest = temperatures[50];
is wrong.
The functions can be written like this function definition
void highest( int days )
{
int highest = temperatures[0];
for ( int count = 1; count < days; count++ )
{
if ( highest < temperatures[count] ) highest = temperatures[count];
}
cout << "The highest temperature is: " << highest << endl;
}
Take into acccount that there are standard algorithms std::max_element, std::min_element, std::minmax_element declared in header <algorithm> that can be used instead of your functions.
For example function highest can be defined with using standard algorithm std::max_element the following way
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
Array indices start with a 0
Place the cout statements outside the for loop.
Arrays are indexed from 0 to n-1, where n is the total number of entries in the array. You started the count at 1 in your loop when you should start at 0. If the user entered 50 values, you would have had an out-of-bounds access.
The correction should be:
for (int i = 0; i < days; i++)
Then in your output statement, it should be:
cout << "Enter the temperature for day number " << i+1 << ": ";
The other issue is your highest function. The issue are a few things:
You declared the local variable highest as an int. It should be a float to match the type used in the temperature array.
You should set highest to a very small value, smaller than any you would expect. Or better yet, set it to the first temperature entry before the loop, and start the loop from the second entry.
You named your local variable highest, but your function name is also highest. This will lead to confusion when someone else looks at your code.
If you're interested in another solution, the following computes the highest:
#include <algorithm>
//...
void highest(int days)
{
float theHighest = *std::max_element(temperatures, temperatures + days);
cout << "The highest temperature is: " << theHighest << endl;
}
A little better version from the function 'highest':
void highest(int days)
{
if (days < 1)
{
cout << "No temperatures" << endl;
}
double highest = temperatures[0];
for (int count = 1; count < days; count++)
{
if (temperatures[count] > highest)
{
highest = temperatures[count];
}
}
cout << "The highest temperature is: " << temperatures[highest_index] << endl;
}
All arrays in C++ starting with index 0. In this implementation this point is considered by using the first element (index 0) as thie first highest value. After that the loop has only to deal with the rest, begining at index 1.
The variable 'highest' must be from the type double. Otherwise you may get wrong results, because the highest is a little lower than the real highest due to generaly rounding down (double to int). The next comparison may be assigned even if it is a little lower.
Array indices start with 0 but your loops start at 1. For your loop over days, for instance, this will iterate over the full range:
for (int i = 0; i < days; i++)