The program requires the user to input numbers and when finished to exit the loop by entering a negative number. The program will then output the average of the numbers and the count of the numbers. The negative number should be removed from the series though. So if we have three numbers and exit on the (fourth) negative number, the average will only be of the three numbers and not include the negative number. Neat, I somehow made that work. Now, I need to expand upon this to make it so that the input is verified to be an integer and less than 100 also using a Boolean equation. It is at this point that I cannot determine how to exclude the erroneous input from the results.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float inScore= 1;
float sumScore= 0.0;
int scoreCount= 0;
float avgScore= 0.0;
bool moreNumbers = true;
bool notNumbers = true;
for ( inScore =1; inScore >=1; inScore++) //for loop some kind of blackmagic not really sure about this right now
{
cout << "Please enter grades (enter a negative integer to exit): ";
cin >> inScore;
if (!cin || inScore > 100)
{
notNumbers = false; //boolean to ignore non integers or numbers greater than 100
cin.clear();
cin.ignore(256, '\n');
scoreCount--;
cout << "Invalid number!" << endl;
} //something is wrong in this section and I can't get it to ignore the invalid inputs
else if (inScore < 0)
{
moreNumbers = false;
} //breaks the loop upon a negative number being entered
else
sumScore+=inScore;
scoreCount++;
}
avgScore = (sumScore+=inScore)/(scoreCount-1);
cout << "Number of Grades: " << scoreCount-1 << endl; //number of entries
cout << "Average: " << avgScore << endl; // average grade except I cannot figure out how to remove negative number from the array
return 0;
}
Related
I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.
I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.
The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.
Examples of the problem I am having:
If I input 5 for the first value, it asks me to enter 5 integers.
After entering 4 numbers, 1 2 3 and 4.
It tells me the max is 4 and min is 1.
It prevents me from entering in the 5th integer.
Additionally,
If I input 5 for the first value, it asks me to enter 5 integers.
If I enter a negative number, like -1, the input allowed to me is further
shortened.
If I enter -1, 2, 3 then the output is min: 2 and max: 3
I have two main questions:
What adjustments do I need to make to my code so that I can properly
enter in the number of integers initially asked for?
What adjustments need to be made in order for me to be able to enter
negative integers so they are outputted correctly?
The code:
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num = 0;
int min_num;
// prompt user for integer amount
cout << "How many integers would you like to enter? " << endl;
cin >> input;
cout << "Please enter " << input << " integers." << endl;
tmp = input;
// loop for requested amount with a test for each input
while (counter <= tmp) {
cin >> input;
// if smaller than previous number it is the minimum
if (input < min_num || min_num == -1) {
min_num = input;
counter++;
}
// if larger than previous number it becomes max number else
if (input > max_num) {
max_num = input;
counter++;
} else { // continue loop if number isn't bigger than max or smaller than min
counter++;
}
}
// display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;
return 0;
}
I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;
I'm very new to C++ and have an assignment to edit this code to make it work. For some reason, when I use a combination of multiple positive or negative numbers, it gives the answer that I've entered multiple numbers an extra number.
Example:
I enter 3 postive numbers and 1 negative number. The counter displays 4 positive and 1 negative. Same thing happens if I start with negative numbers instead of positive.
Any help would be greatly appreciated. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int positive = 0; //counter
int negative = 0; //counter
int totalPositive = 0;
int totalNegative = 0;
//get a number
cout << "Enter a positive or negative integer (enter 0 to end): ";
cin >> number;
while (number != 0)
{
//update counters
if (number > 0)
{
positive =+ 1;
}
else
negative =+ 1;
//end if
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
cin >> number;
totalPositive += positive;
totalNegative += negative;
}//end while
//display counters
cout << endl;
cout << "Total positive numbers: " << totalPositive << endl;
cout << "Total negative numbers: " << totalNegative << endl;
system("pause");
return 0;
} //end of main function
Try this code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int number;
int positive = 0;
int negative = 0;
do{
cout << "Enter a positive or negative integer (enter 0 to end): ";
cin >> number;
if (number > 0)
positive += 1;
else if(number<0)
negative += 1;
}while(number!=0);
//end while
//display counters
cout << endl;
cout << "Total positive numbers: " << positive << endl;
cout << "Total negative numbers: " << negative << endl;
system("pause");
return 0;
} //end of main function
You don't have to use total positive and total negative, unless you want to have the summation of the positive numbers and the negative ones.
positive is accumulating, but totalPositive is accumulating your accumulation. Try totalPositive++ (and the negative version) in your if statement, and eliminate variables positive and negative.
The logic error in your program is that positive and negative never get reset to 0 once they are set to 1.
If your first two numbers are such that one is a negative number and the other is a positive number, totalPositive and totalNegative will keep increasing after that regardless of the value of number.
You can simplify your logic to:
//get a number
cout << "Enter a positive or negative integer (enter 0 to end): ";
while (cin >> number && number != 0)
{
//update counters
if (number > 0)
{
++totalPositive;
}
else
{
++totalNegative;
}
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
}//end while
Firstly note the =+ is not an operator (Unlike += which increments the value)
The line
positive =+ 1
is just interpreted as assigned +1 to positive (which is what you want) but can be just written as
positive = 1
This though brings us to the actual point which is that you don't reset positive or negative back to zero each time around the loop.
Once both positive and negative are assigned to 1 (i.e. when you have entered at least one of each), every time both totalPositive and totalNegative will be incremented.
You may want to consider whether you need the variables positive or negative at all.
SOmething that might help is to do this for the while loop instead
while (number != 0)
{
positive = 0;
negative = 0;
//update counters
if (number > 0)
{
positive = 1;
}
else
negative = 1;
//end if
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
cin >> number;
totalPositive +=positive;
totalNegative +=negative;
}
Otherwise you're doing this thing that's basically 1 + 2 + 3 + 4... for every time the loop runs. By setting each value to 0, it ensures that totalPositive only increases once every loop. Otherwise it grows exponentially
Well your counters are not reset to 0 after your loop finishes.
When you enter your loop the first time, the counters are 0 (positive, negative), but the second time around, the counters are still 1, resulting in a bad counter.
When entering the loop:
positive = 0;
negative = 0;
//update counters
This code, could be highly refactored to be more efficent, but that's for another question.
My assignment is to create a program in which the user inputs a starting value and ending value. The program should then sum all the numbers within that range. In addition it should sum the odd numbers and the even numbers. My issue is determining which numbers in the users range is odd and which is even and then summing these values. The total sum loop works but I have tried multiple other loops for the odd and even sums and have had no success. So if someone could help me sum these numbers based on whether there even or odd.
#include <iostream>
using namespace std;
int main()
{
int sum = 0, start, endnumber;
int sumall = 0, c=0;
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
while (endnumber <= start)
{
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
}
while (start <= endnumber)
{
sumall = sumall + start;
++start;
}
std::cout << "The sum is: " << sumall << std::endl;
return 0;
}
You need to check each number in the range with modulo.
For ex:
if( start%2 == 0 ) // even
{
evenSum+=start;
}
else // Odd
{
oddSum+=start;
}
That will do the job.
You can test for odd numbers by anding with 1.
if ((start & 1) == 0)
evenSum += start;
else
oddSum += start;
Small note when talking to mathematicians: don't use modulo and modulus interchangeably (even though wikipedia says they are the same):
modulo is % for positive numbers.
modulus is the abs function.