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.
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.
Hello I'm trying to display only the amount of odd/even numbers for the digits entered. I've tried multiple methods but failed to find any solution. This is the problem and what I have so far.
Write a program that allows the user to enter 10 separate whole numbers. After accepting these 10 numbers from the user, the program should display output to the user informing them how many of the numbers entered were odd numbers and how many were even numbers.
#include <iostream>
using namespace std;
int main() {
char even, odd;
int number;
for(int i = 1;i<=10;i++) {
cout << "Enter Number " << i << ":" ;
i=i+0;
cin >> number ;
}
if (number%2==0){
number = even;
}
cout<< "You entered:\n";
cout << "Odd Numbers: " << odd << endl;
cout << "Even Numbers: " << even << endl;
return 0;
}
There are a few things in your code that do not look right.
for(int i = 1; i <= 10; i++)
{
cout << "Enter Number " << i << ":";
i = i + 0;
cin >> number;
}
What are you hoping to accomplish with the line i = i + 0? Your loop will work just fine without it.
char even, odd;
Technically, since char is a numeric type, you may keep track of the number of even and odd numbers encountered by keeping track of them. However, you aren't doing that.
The statement:
if (number%2==0){
number = even;
}
Is saying that if the input number is even, assign the current value of char even to number. However, this doesn't make sense, since you never stored a value in even earlier. Also, you're doing this outside the loop, so effectively only the last of the 10 values read into number would ever be counted in your calculations (if you had that done correctly).
What you should do:
int even = 0, odd = 0;
for(...)
{
// read input into "number"...
if(number % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
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;
}
Create a program that takes as input a string of digits and outputs
the sum of the even and the sum of the odd digits. This program is in
C++
NOTE: It is recommended that you use a "for" loop to iterate over the
sting of digits. HINT: Use the modulus operator to determine even or
odd digits.
A clever method of converting a "char" to an "int" is as follows link:
char a = '4';
int ia = a - '0';
The above code takes advantage of the character's position in the
ASCII table to convert it to an integer.
Below is the code I have so far:
int main() {
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
int digits; // Sum from 1 to this upperbound
// Prompt user for an upperbound
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
cin >> digits;
// Use a while-loop to repeatedly add 1, 2, 3,..., to the upperbound
int number = 1;
while (number <= digits) {
if (number % 2 == 0) { // Even number
sumEven += number; // Add number into sumEven
} else { // Odd number
sumOdd += number; // Add number into sumOdd
}
++number; // increment number by 1
}
// Print the results
cout << "The string of digits \"" << digits << "\""
<< " contained "
<< "characters." << endl;
cout << "The sum of the even digits is: " << sumEven << endl;
cout << "The sum of the odd digits is: " << sumOdd << endl;
return 0;
}
This is my output compared to the output I need
Input:
1234567890
Output:
Please enter a string comprised ONLY of digits:
The string of digits "1234567890" contained characters.
The sum of the even digits is: -380436870
The sum of the odd digits is: -997720815
Expected output
Please enter a string comprised ONLY of digits:
The string of digits "1234567890" contained 10 characters.
The sum of the even digits is: 20
The sum of the odd digits is: 25
Overall I'm having trouble counting the input and getting the correct formula for my even and odd numbers. Any help is appreciated thank you so much!
A simple method is to keep the number in text form:
std::string number_as_text;
cout << "Enter number: ";
cin >> number_as_text;
This allows you to check each digit for even or odd:
const size_t length = number_as_text.length();
for (size_t i = 0; i < length; ++i)
{
char digit_character = number_as_text[i];
if (isdigit(digit_character))
{
if (digit_character % 2 == 0)
{
// digit is even
}
else
{
// digit is odd
}
}
}
If you don't like isdigit(), you can replace with:
if ((digit_character >= '0') && (digit_character < '9'))
An important note is that there is a difference between the textual representation of digits and the internal, numeric, representation of digits.
Edit 1: % on char type
The char data type is an integer. The remainder operator, %, works on integer types. Thus you can use % on char types.
Note: this operation assumes that the character mapping of '0' is an even integer and the other digits are successive in values.
Read the inputs in a string field and not an integer as -
std::string digits;
Then, just run a valid loop to find out the sum of the even digits and the odd digits -
for(int i=0; i<digits.length(); i++){
int digit = digits[i]-'0';
if(digit % 2 == 0)
sumEven+=digit;
else
sumOdd+=digit;
}
Below is a running piece of code.
// Example program
#include <iostream>
#include <string>
using namespace std;
int main() {
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
std::string digits; // Sum from 1 to this upperbound
// Prompt user for an upperbound
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
cin >> digits;
// Use a while-loop to repeatedly add 1, 2, 3,..., to the upperbound
int number = 1;
for(int i=0; i<digits.length(); i++){
int digit = digits[i]-'0';
if(digit % 2 == 0)
sumEven+=digit;
else
sumOdd+=digit;
}
// Print the results
cout << "The string of digits \"" << digits << "\""
<< " contained "
<< "characters." << endl;
cout << "The sum of the even digits is: " << sumEven << endl;
cout << "The sum of the odd digits is: " << sumOdd << endl;
return 0;
}
You got it wrong you are supposed to do sum of 1+3+5+7+9 and sum of 2+4+6+8+0. What are you doing instead is sum of all even numbers smaller than 1234567890 and sum of odd numbers smaller than 1234567890.
Maybe consider instead of getting all numbers in string by cin >> digits read it from input by characters one by one.
Check this code it reads characters from input and spits them back.
#include<iostream>
using namespace std;
int main() {
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
char one;
while ( true ) {
cin >> one;
// here will come your part with deciding even / odd and counting instead of pritnting out.
cout << " " << one;
if ( cin.peek() == '\n' ) { break; }
}
return 0;
}
And now it's your turn to put it together.
Use std::getline to read all digits into a std::string:
std::cout << "Enter string of numbers: " << std::endl;
if (std::string numbers; std::getline(std::cin, numbers)) {
/* ... */
}
Note the use of conditional-if above from the upcoming C++1z standard.
Then, you could make use of std::pair to neatly accumulate the odds and evens like this:
std::pair odd_even{0, 0};
for (auto c : numbers) {
(c % 2 ? std::get<0>(odd_even) : std::get<1>(odd_even)) += c - '0';
}
Live example
This one logically should work
for(int i=0; i<digits.lenght; i++){
if(digits[i] % 2 == 0)
sumEven+=digits[i];
else
sumOdd+=digits[i];
}
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.