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");
}
Related
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;
}
I started to learn C++ and my homework is to write a code where you can enter 5 numbers and the program will tell you for each number whether it is a Fibonacci number or not.
I also tried using a do/while-loop in the isFibonacci function instead of the for-loop, but that did not fix the problem.
#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i)
{
//special cases with 0 and 1:
if ( i == 0 || i ==1) {
return true;
}
//for all other numbers:
int Fib1;
int Fib2;
int Fib3;
for (Fib3=0; Fib3>=i; Fib3++) {
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
if (Fib3==i){
return true;
}
else {
return false;
}
}
}
int main ()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
cout << "Please enter 5 numbers;" << endl;
cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i=0; i<5; i++) {
result=isFibonacci (numbers[i]);
if (result == true) {
cout << "Your number " << numbers[i] << " is a Fibonacci number!" << endl;
}
else {
cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
}
}
return 0;
}
The first Fibonacci numbers are (0),1,1,2,3,5,8,12.
So when I enter 5 numbers, for example 1,2,3,4,5 I should get a "yes" for 1,2,3 and 5, but a "no" for 4.
However, my program claims that except for 1, none of these numbers are Fibonacci numbers.
Basically your approach was a good idea. But you made some implementation errors in your check function. Like not initialized variables and wrong calculations. And look at you for loop.
Additionally. There will be a problem with big numbers.
Many very smart people, explored the Fibonacci numbers. There are whole books available. Also a Wikipedia article. See here.
Or look into that book:
The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
Or also here on stackoverflow
Therefore I will not reinvent the wheel. Here is your revised software:
#include <iostream>
#include <cmath>
#include <numeric>
// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
{
double x1 = 5 * std::pow(w, 2) + 4;
double x2 = 5 * std::pow(w, 2) - 4;
long x1_sqrt = static_cast<long>(std::sqrt(x1));
long x2_sqrt = static_cast<long>(std::sqrt(x2));
return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
}
}
int main()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
std::cout << "Please enter 5 numbers;" << std::endl;
std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i = 0; i < 5; i++) {
result = isFibonacci(numbers[i]);
if (result == true) {
std::cout << "Your number " << numbers[i] << " is a Fibonacci number!" << std::endl;
}
else {
std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
}
}
return 0;
}
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!
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.