My problem is finding the minimum value out of user defined number of inputs. Everything so far works just fine, except that. Every time I try and rearrange some code or try a new method, I keep getting the same output on the screen:
Sum of numbers entered is: 145.4
Average of numbers entered is: 24.2333
The Highest number entered was: 45
The Lowest number entered was: 6.95283e-310
I get this every single time, regardless of what is entered, or what different suggestion I try:
The Lowest number entered was: 6.95283e-310
I am aware of the use and implementation of Arrays. However, the assignment I'm doing hasn't even covered arrays yet. That is some number of chapters later. Please don't suggest arrays...
I've looked here:
Finding Maximum and Minimum values in c++ by user input
Didn't work
http://www.cplusplus.com/forum/beginner/38799/
Didn't work
changing the values of max/min didn't work either
#include <iostream>
using namespace std;
int main()
{
double number, numberitems, sum = 0, average, max, min;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
max = number;
}
//minimum value entered
if (number < min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
std::cout << endl;
std::cout << endl;
std::cout << "Sum of numbers entered is: " << sum << '\n';
std::cout << "Average of numbers entered is: " << average <<'\n';
std::cout << "The Highest number entered was: " << max <<'\n';
std::cout << "The Lowest number entered was: " << min <<'\n';
return 0;
}
Made a temporary fix :3
double min = 99999999999999999999999999999999999999999999999;
I'm very new to this.
Updated
After reading more comments I saw I was missing <cfloat>. Using #include <cfloat> NOW everyone's suggestions above work. However, <cfloat> was not covered in class, at all. So I'm not sure if that is usable here?
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
int numberitems;
double number, sum = 0, average;
double max = 0;
double min = DBL_MAX;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number >= max) {
max = number;
}
//minimum value entered
if (number <= min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
std::cout << "I said not to enter a negative number...'\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
//Print the results
// some cosmetic...
std::cout << endl;
std::cout << endl;
std::cout << "\n=================REPORT====================\n";
std::cout << '\n';
std::cout << "\tYour Totals\tValues\n";
std::cout << "\t-----------\t------\n";
std::cout << "\t Sum: " << sum << '\n';
std::cout << "\t Average: " << average <<'\n';
std::cout << "\t Highest: " << max <<'\n';
std::cout << "\t Lowest: " << min <<'\n';
return 0;
}
Again, <cfloat> works fine, but I'm not sure if I'm allowed to use it. What other ways around this are there?
The question already got good answers - shortly: min and max are uninitialized.
However
Above is very specific.
Of course it helps in this specific case but I feel a broader advise that would work here and in many other cases is needed.
Add printouts
Adding debug printouts to your code ("debugging without a debugger") is always helpful in such cases.
For example adding the following in your example may help:
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
// debug - (remove before submission)
std::cout << "number is the new max! number = " << number
<< ", max = " << max << std::endl;
// end of debug
max = number;
}
//minimum value entered
if (number < min) {
// (debug - remove before submission)
std::cout << "number is the new min! number = " << number
<< ", min = " << min << std::endl;
// end of debug
min = number;
}
When calculating minimum and maximum, you should initialize your variables to a default value. For minimum, it's the maximal possible value; for maximum - the minimal possible one.
double max, min; // BUG - not initialized
#include <float.h> // or <cfloat>
...
double max = 0; // CORRECT - initialized
double min = DBL_MAX; // CORRECT - initialized
For maximum, the initialization is usually -DBL_MAX (note: not DBL_MIN), but 0 is good enough in this case, when no negative values exist.
You need to set an initial value for min and max. For min, I'd suggest using an initial value of DBL_MAX, which is defined in the header cfloat.
Related
I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.
I get to put in the first number but then the for loop does not work.
#include <iostream>
#include <vector>
int main() {
int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;
std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";
for (int i = 1; i <= totalNum; i++){
std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];
if (numbers[i] % 2 == 0) {
total_even = total_even + numbers[i];
} else {
product_odd = product_odd * numbers[i];
}
}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}
First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).
Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out (0 + a + b == a + b, 1 * a * b == a * b). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.
By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):
#include <iostream>
int main() {
int numCount, thisNum, sumEven = 0, productOdd = 1;
std::cout << "How many numbers would you like to enter? ";
std::cin >> numCount;
std::cout << "\n";
for (int i = 1; i <= numCount; i++) {
std::cout << "Please enter number #" << i << ": ";
std::cin >> thisNum;
if (thisNum % 2 == 0) {
sumEven += thisNum;
} else {
productOdd *= thisNum;
}
}
std::cout << "\nSum of even: " << sumEven << "\n";
std::cout << "Product of odd: " << productOdd << "\n";
}
A sample run:
How many numbers would you like to enter? 6
Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6
Sum of even: 12
Product of odd: 15
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.
I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}
I've just started learning C++ and I'm working by myself through Bjarne Stroustup's P:P&P.
I am on the Chapter 4 drill.
The problem I am having seems to lie within the order of the program. If I add another closing curly brace right before the vector to close the while-statement, I get the right output for max_val and min_val. However by adding that brace, the double named sum remains at zero even though I want sum to increment by the double named number.
If I compile the program as it is written now (without the addition of the extra curly braces), I get the wrong output for min_val and max_val but the proper output for sum.
Also, as you can see at the bottom of the program, the line:
cout << " values were entered." << '\n'; is not complete. I wanted to print out the number of total values entered but left it incomplete due to frustration and need of help. I am very new to programming and any constructive criticism, no matter how harsh, would be appreciated.
#include "std_lib_facilities.h"
int main()
{
double value = 0;
double max_val = 0;
double min_val = 0;
string unit =" ";
double sum = 0;
cout << "Enter some numbers, followed by a unit of distance (m, cm, ft, inch):" << '\n';
while (cin >> value >> unit){
//determines entered value as max/min/both/neither
if (min_val == 0 && value > max_val){ // first number entered is both largest and smallest
max_val = value;
min_val = value;
cout << value << " metres is both the smallest and largest so far" << '\n';
}
else if (value < min_val){// smallest number min_val = value;
cout << min_val << " metres is the smallest so far." << '\n';
}
else if (value > max_val){// largest number max_val = value;
cout << max_val << " metres is the largest so far." << '\n';
}
else { // number between smallest and largest
cout << value << " metres is neither the smallest or largest." << '\n'; }
//convert entered unit to metres
if (unit == "m"){
value = value;
}
else if (unit == "cm"){//converts cm to metres
value = value/100;
}
else if (unit == "ft"){//converts ft to metres
value = value/3.28084;
}
else if (unit == "inch"){//converts inch to metres
value = value/39.3701;
}
else{
cout << "I dont know the unit " << unit << ".";
}
vector <double> numbers; //reads input into vector
double number = 0;
while (cin >> number) numbers.push_back(number);
for (double number: numbers) sum += number;
cout << "The largest value entered was: " << max_val << "." << '\n';
cout << "The smallest value entered was: " << min_val << "." << '\n';
cout << "The sum of the numbers entered is: " << sum << "metres" <<'\n';
cout << " values were entered." << '\n';
keep_window_open("~");
return 0;
}
Here is a small insight regarding the input loop, finding min_value, max_value and sum:
#include "../../std_lib_facilities.h"
int main(){
// vector holding the input values
vector<double> inputValues;
// vector-input variable
double temp = 0;
// variable holding the sum of the input
double sum = 0;
// variables holding the minimum and maximum input value
double minVal = 100000; // note the initialization values
double maxVal = -100000;
vector<string>units;
string unit;
// prompt message; value input
cout << "Enter the first value: ";
while (cin >> temp >> unit) {
cout << "Enter the next value: ";
inputValues.push_back(temp);
units.push_back(unit);
}
// conversion...
for (int i = 0; i < inputValues.size(); ++i){
if (inputValues[i] > maxVal){ maxVal = inputValues[i]; }
if (inputValues[i] < minVal){ minVal = inputValues[i]; }
sum += inputValues[i];
}
// print result
cout << "Minimum temperature = " << minVal << endl;
cout << "Maximum temperature = " << maxVal << endl;
cout << "Average temperature = " << sum/inputValues.size() << endl;
return 0;
}
For the conversion you can use a second container, e.g. vector to store the units and then create a loop using the same index for both values and units, with a if, else if block for each unit conversion:
vector<string> units;
for(int i = 0 ; i < inputValues.size(); ++i){
if(units[i] == "cm") inputValue[i] = inputValue[i] / 100.;
else if(units[i] == "...") inputValue[i] =...;
// ...
}
Note:
the input loop needs improvement, e.g. termination condition, think about termination keyword with do-while loop, handling of wrong input types, cin.clear(), etc.
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++)