Bjarne Stroustrup's P:PP Chapter 4 Drill - c++

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.

Related

Finding the minumum value out of user inputs in C++

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.

Exercise about loops and arrays - use loops 1 time and how to get the max value of an array

I know just a little about programming but I'm pretty new to C++. I just started to study it one week ago and I'm posting a question about the code I wrote since I can't solve few small problems.
The program I wrote asks how many elements you'd like to analyze and it returns the sum of the elements, how many even and odd numbers you inserted, the sum of the odd and even numbers only and it should returns the maximum (and minimum) value.
This is the code:
#include <iostream>
using namespace std;
int elements, sum = 0, x, arr[10], even = 0, odd = 0, evenSum = 0, oddSum = 0,
mx; //Variable declaration
int main() {
cout << "Type how many elements you would like to sum and analyze" << endl; //Input of the numbers of elements to analyze
cin >> elements;
if (elements > 10)
cout << "Too many elements" << endl; //If the elements are more than 10, the program quit
else {
for (x = 1; x <= elements; x++) {
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> arr[x];
}
for (x = 1; x <= elements; x++) { //Sum of the elements of the array
sum += arr[x];
}
mx = arr[0];
for (x = 1; x <= elements; x++) { //Find the maximum value of the array
if (arr[0] >= mx) {
mx = arr[0];
}
}
for (int x = 1; x <= elements; x++) { //Count and sum of the even elements
if (arr[x] % 2 == 0) {
even++;
evenSum += arr[x];
}
if (arr[x] % 2 != 0) { //Count and sum of the odd elements
odd++;
oddSum += arr[x];
}
}
cout << "The sum of the elements of the array is: " << sum << endl; //Outputs
cout << "The max value of the array is: " << mx << endl;
cout << "Even numbers are: " << even << endl;
cout << "Odd numbers are: " << odd << endl;
cout << "The sum of even numbers is: " << evenSum << endl;
cout << "The sum of odd numbers is: " << oddSum << endl;
}
return 0;
}
My questions are:
Do I have to repeat the "for" loop 4 times or, since the conditions
of the loops are the same, I can write it only one time followed by the code to execute?
To calculate the maximum value, I used as a variable name "max" but the editor doesn't compile. I changed the name from "max" to "mx"
and it compiles. Is "max" a reserved word for C++? What is wrong?
Why the program always gives "0" as the maximum value of the array? I can't understand what is wrong in the algorithm and I can get the maximum value of the listed elements.
Thank you very much for the support.
Matteo
Code cleansing 101:
There are several things to make your code much cleaner.
1) You don't need that many for loops and since you don't need that many for loops you can get rid of your array.
2) Your variables should be local not global.
3) Several of your variables were not initialized to 0 thus you can't do odd++; (for example)
Look through my changes, understand them, read the comments, and ask questions if you have them :)
#include <iostream>
using namespace std; //probably don't want to use this here
int main()
{
// keep these variables local instead of global
int elements, sum , even, odd, evenSum, oddSum, mx;
sum = even = odd = evenSum = oddSum = mx = 0; //set them all to 0
cout << "Type how many elements you would like to sum and analyze" << endl; //Input of the numbers of elements to analyze
cin >> elements;
if (elements > 10)
cout << "Too many elements" << endl; //If the elements are more than 10, the program quit
else
{
// An array is based on the 0 index not the 1 index.
// so the first value in array as at x = 0 and the second is at x = 1 and so on
int currentNum;
for (int x = 0; x < elements; x++) //int x = 0 and x < elements
{
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> currentNum;
sum += currentNum;
if (currentNum >= mx)
mx = currentNum;
if (currentNum % 2 == 0)
{
even++;
evenSum += currentNum;
}
if (currentNum % 2 != 0) { //Count and sum of the odd elements
odd++;
oddSum += currentNum;
}
}
cout << "The sum of the elements of the array is: " << sum << endl; //Outputs
cout << "The max value of the array is: " << mx << endl;
cout << "Even numbers are: " << even << endl;
cout << "Odd numbers are: " << odd << endl;
cout << "The sum of even numbers is: " << evenSum << endl;
cout << "The sum of odd numbers is: " << oddSum << endl;
}
return 0;
}
You should be able to calculate everything inside a single for-loop, yes.
This might be because you have the line
using namespace std;
at the top of your file. When you write max the compiler assumes that you mean the function std::max: http://en.cppreference.com/w/cpp/algorithm/max
You could try removing the using namespace std; and instead insert std:: where needed, e.g. std::cin, std::cout and std::endl.
There are two problems. First of all you have typos here:
if (arr[0] >= mx) {, mx = arr[0];
Replace 0 with x. The second problem occurs if you only enter negative numbers. You don't have an explicit initialization for mx, so it will be initialized to zero. If you only enter negative numbers then your program will incorrectly say that zero is greatest number. You should probably initialize mx to the lowest possible number for its type, e.g.: std::numeric_limit<int>::min().
First, if you have index based-0, you don't read arr[0] in first loop
for (x = 1(error, it should be 0); x <(only '<') elements; x++) {
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> arr[x];
}
Now, you can do all in two loops.
#include <iostream>
using namespace std;
int elements, sum = 0, x, arr[10], even = 0, odd = 0, evenSum = 0, oddSum =
0,
mx; //Variable declaration
int main() {
cout << "Type how many elements you would like to sum and analyze" << endl; //Input of the numbers of elements to analyze
cin >> elements;
if (elements > 10)
cout << "Too many elements" << endl; //If the elements are more than 10, the program quit
else {
for (x = 0; x < elements; x++) {
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> arr[x];
}
mx = arr[0];
for (x = 0; x < elements; x++) { //Find the maximum value of the array
sum += arr[x];
if (arr[x] >= mx) {
mx = arr[x];
}
if (arr[x] % 2 == 0) {
even++;
evenSum += arr[x];
}
if (arr[x] % 2 != 0) { //Count and sum of the odd elements
odd++;
oddSum += arr[x];
}
}
cout << "The sum of the elements of the array is: " << sum << endl; //Outputs
cout << "The max value of the array is: " << mx << endl;
cout << "Even numbers are: " << even << endl;
cout << "Odd numbers are: " << odd << endl;
cout << "The sum of even numbers is: " << evenSum << endl;
cout << "The sum of odd numbers is: " << oddSum << endl;
}
return 0;
}
Alto you can do all in one loop
#include <iostream>
using namespace std;
int elements, sum = 0, x, arr[10], even = 0, odd = 0, evenSum = 0, oddSum =
0,
mx; //Variable declaration
int main() {
cout << "Type how many elements you would like to sum and analyze" << endl; //Input of the numbers of elements to analyze
cin >> elements;
if (elements > 10)
cout << "Too many elements" << endl; //If the elements are more than 10, the program quit
else {
mx = arr[0];
for (x = 0; x < elements; x++) {
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> arr[x];
sum += arr[x];
if (arr[x] >= mx) {//error here, you need compare arr[x], not arr[0]
mx = arr[x];
}
if (arr[x] % 2 == 0) {
even++;
evenSum += arr[x];
}
if (arr[x] % 2 != 0) { //Count and sum of the odd elements
odd++;
oddSum += arr[x];
}
}
cout << "The sum of the elements of the array is: " << sum << endl; //Outputs
cout << "The max value of the array is: " << mx << endl;
cout << "Even numbers are: " << even << endl;
cout << "Odd numbers are: " << odd << endl;
cout << "The sum of even numbers is: " << evenSum << endl;
cout << "The sum of odd numbers is: " << oddSum << endl;
}
return 0;
}
Good point about the array indexing! I know an array is 0-indexed but even starting from 1 the program works fine!
I type 5 as a number of elements to analyze and a I can insert, for instance, 1 2 3 4 5, having the correct outputs:
Sum: 15
Odd elements: 3
Even elements: 2
I can't understand why!

How to take an average of values entered into a C++ program?

Here is what I have. I have notes in the code where I'm having trouble towards the bottom. I'm trying to find the total average of the grades entered by the user. The user has put in four different grades near the bottom. They are weighted as 10% of the grade.
The Programs are 30% and the exercises are 10%. The final Exam is 30%. Please just give me advice on what to do. Don't tell me the code. I want to try and figure the code out on my own before asking for additional help so that I learn this. I just want advice on what steps to take next. Thanks.
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
float average(const vector<float> &values);
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Program 11" << endl;
cout << "December 8th 2016" << endl;
cout << endl;
cout << endl;
vector<float> exerciseGradesVector;
float exerciseGrades;
cout << "Enter the grades for the Exercises. Type 1000 when you are finished." << endl;
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
cout << endl;
cout << "You entered " << exerciseGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Exercise grades you entered are : ";
for(int i=0; i < exerciseGradesVector.size(); i++)
{
cout << exerciseGradesVector[i] << " ";
}
cout << endl;
float averageExerciseGrades = average( exerciseGradesVector );
cout << "The average of the Exercise grades is: " << averageExerciseGrades << endl;
cout << endl;
vector<float> programGradesVector;
float programGrades;
cout << "Enter the grades for the Programss. Type 1000 when you are finished." << endl;
while ( std::cin >> programGrades && programGrades != 1000 )
{
programGradesVector.push_back (programGrades);
}
cout << endl;
cout << "You entered " << programGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Program grades you entered are : ";
for(int i=0; i < programGradesVector.size(); i++)
{
cout << programGradesVector[i] << " ";
}
cout << endl;
float averageProgramGrades = average( programGradesVector );
cout << "The average of the Program grades is: " << averageProgramGrades << endl;
cout << endl;
float midTermTest;
float midTermProgram;
float finalExamTest;
float finalExamProgram;
cout << "Please enter the Midterm Exam score for the multipule choice section. " << endl;
cin >> midTermTest;
cout << "Please enter the Midterm Exam score for the Programming section. " << endl;
cin >> midTermProgram;
cout << "Please enter the Final Exam score for the multipul choice section. " << endl;
cin >> finalExamTest;
cout << "Please enter the Final Exam score for the Programming section. " << endl;
cin >> finalExamProgram;
///////I need to find the average off ALL the grades.. All the 4 inputs above and the two vectors need to be in the average.
///////I am not sure if I need to read the 3 numbers before the last one into a vector because each is worth 10 percent and then do the next step or what. Would that mess it up? Advice please?
vector<float> allGradesVector;
float totalaverageGrade = average( allGradesVector ); //This is obviously not finished. Just ignore it..
}
float average( const vector<float> &values )
{
float sum = 0.0;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
I would suggest to rewrite the loops like this
do
{
cin >> exerciseGrades;
exerciseGradesVector.push_back (exerciseGrades);
}
while (exerciseGrades != 1000);
the following way
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
In this case there is no need to use a strange variable like dropOne.
To find the average is easy. The function can look the following way
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( float x : values ) sum += x;
return values.size() == 0 ? sum : sum / values.size();
}
Or if the compiler does not support the range-based for loop you can write
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
To call the function you can write for example in main
float averageExerciseGrades = average( exerciseGradesVector );
The function must be declared before its usage that is for example before main
float average( const std::vector<float> &values );
though it may be defined after main.
A simple for loop will do the trick.
float total = 0;
int count = 0
for(int i = 0; i < dropOnee; i++)
{
total+= programGradesVector[i];
count++;
}
cout << "The average is: " total/count << endl;
I'd also recommend using more descriptive name's for the counts.
You can use std::accumulate
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
I would suggest to use while to replace do while. Because you may input 1000 firstly.
You can write like this:
while ( std::cin >> exerciseGrades && fabs(exerciseGrades - 1000) < 0.000001 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
I use fabs function to solve float is inaccuracy in sometime.
About averages function:
You can use std::accumulate:
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
or implement it by yourself like this:
float average( const std::vector<float> &values )
{
float sum = 0.0f;
int nSize = values.size();
for(int i = 0; i < nSize; ++i)
{
sum += values[i];
}
return nSize == 0 ? sum : sum / nSize;
}

Exercise: for cycle and array

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 )
{
// ...
}

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");
}