I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)
Related
I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.
I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.
I was tasked with writing some code that will take a user input and convert the number to its binary number. I have written some code so far, but am having one issue. I have to use a for loop and the quotient-remainder method. When I output the remainder(binary), it is not printing the last digit.
The question I'm asking is: What would I have to change in my for loop to make it print out the last digit of the binary number?
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
for (int i = 0; i <= (num + 1); i++)
{
num /= 2;
rem = num % 2;
cout << rem;
}
_getch();
return 0;
}
Any help is appreciated, Thank you!
You lose the last binary number when you start your algorithm by dividing num by 2. To avoid this issue, you should exchange both instructions num /= 2; and rem = num % 2;
Your loop also iterates too many times: in fact you can stop when num == 0. The following code is not valid for inputs that are <= 0.
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
while (num != 0)
{
rem = num % 2;
num /= 2;
cout << rem;
}
cout << std::endl;
return 0;
}
If you want to write it in the right order, you should first compute the log of your number in base 2. The following solution uses a number index that starts with '1' and that has '0' after:
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
if (num > 0) {
int index = 1;
while (index <= num)
index *= 2;
index /= 2;
do {
if (num >= index) {
cout << '1';
num -= index;
}
else
cout << '0';
index /= 2;
} while (index > 0);
cout << std::endl;
}
else
cout << '0';
cout << endl;
return 0;
}
You need to change your lines from
num /= 2;
rem = num % 2;
to
rem = num % 2;
num /= 2;
This would print the binary number in reverse order. I would recommend changing the for loop to while(num>0) and adding each digit to an array instead of cout. Print the array from left to right later on to get the correct binary order.
The idea is to use math. Convert the base 10 integer to base 2. The other way maybe is to transverse the bits by testing the integer value against powers of 2 up to maximum bit value for integer. I also assume that you are not going to use floating point numbers. Converting to floating point binary values are a headache.
I'm starting learning C++ on my own and I'm confused with one assignment which I'm trying to complete. User shoud type in natural numbers as long as he wants until he types in 0. After that my program should find the largest sum of digits which were typed and print it out. It shoud also print out a number from which it took the sum.
Here is what I tried to do:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int input = 0;
int digit;
int sum = 0;
int largest = 0;
do
{
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
while (input > 0)
{
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
largest = sum;
} while (input);
cout << "Max sum of digits was " << largest << "for" << endl;
}
When I'm running the programm it counts sum of digits from only first typed in number and stop working. When I take while (input > 0) away, it makes a loop, but doesn't count digits.
I'll be very grateful for help and explanation.
P.S. Sorry for my English, I'm not a native speaker.
You seem to have three problems here:
1 - You are trying to use a variable that you essentially set to zero in your while loop
2 - You seem to be looking for the input that is for the largest sum
3 - You are not resetting your sum variable for each input
The solution for the first problem is to "backup" the input into another variable before modifying it and using that variable for the while loop.
That also allows for you to get what the largest number inputted is and store it.
int input = 0;
int inputBackup = 0;
int digit;
int sum = 0;
int largest = 0;
int largestInput = 0;
To add in the inputBackup variable, put it after the cin.
Then set the largestInput in your sum > largest if statement to set the largestInput if it is the largest.
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
inputBackup = input;// This line
sum = 0; // and this line
while (input > 0)
{
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
{
largest = sum;
largestInput = inputBackup;// Store largest input
}
Then change while(input) to while(inputBackup) to check the inputBackup variable instead of the input one.
Change your cout to be like this to add the largestInput variable into it
cout << "Max sum of digits was " << largest << " for " << largestInput << endl;
And your code should be fixed!
Happy Coding!
do
{
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
//more code
} while (input);
To make this work correctly, input may not change between the cin and the loop condition.
But
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
does change input.
Replace it with something like
int input2 = input;
while (input2 > 0) {
digit = input2 % 10;
sum = sum + digit;
input2 = input2 / 10;
}
In this part:
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
while input is not zero it'll repeat, so when get out the loop the value of input is 0. Use a auxiliary variable or enclose this code on a function:
int getDigitsSum(int input) {
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
return sum;
}
Try that instead
If we do not zero sum value, it accumulate sum of all input digits and the sum will always be larger than than largest value, bacause it stores largest + sum of current values digits. So, if we zero sum value it only contains sum of digits of current input and can be simple compared with previous one wich was largest.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
int input = 0;
int digit;
int sum = 0;
int largest = 0;
do
{
while (input > 0) {
digit = input % 10;
sum = sum + digit;
input = input / 10;
}
if (sum > largest)
largest = sum;
sum = 0; // set to 0 current sum
cout << "enter a natural number (0 if done): " << flush;
cin >> input;
} while (input);
cout << "Max sum of digits was " << largest << " for" << endl;
_getch();
return 0;
}
Hi can anyone help me in creating a code for the sum of input number in C++.
e.g.
Input: 535
Output: 13
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int i = 0,sum = 0;
int numarray[50];
void calc(int c,string num) {
do {
numarray[i] = num.at(i);
/*sum = sum + numarray[i];*/
sum = sum + num.at(i);
cout << numarray[i] << endl;
i++;
} while(i != c);
cout << sum << endl;
}
int main() {
string num;
int i,charlen;
int numar[50];
int sum=0;
cout << "Input numbers: ";
cin >> num;
charlen = num.length();
calc(charlen,num);
}
While characters are numbers, their values are often not the same as the character they represent. The most common encoding scheme is ASCII encoding.
As you can see in the linked table, the digits don't have the value 1 or 2 etc. Instead they have values like 49 and 50 etc. The characters '5' and '3' have the ASCII values 53 and 51 respectively, adding e.g. "535" will give you the result 157.
But as you can see in the ASCII table, all numbers are consecutive, that means we can use a very simple trick to get the digits value from its ASCII value, simply subtract the ASCII value of '0'. For example '5' - '0' will give you the value 5.
Without testing:
#include <iostream>
int main()
{
unsigned long long x;
std::cout << "Enter a non-negative number: ";
std::cin >> x;
unsigned long long sum = 0;
do { sum += x % 10; } while ( x /= 10 );
std::cout << "\nThe sum of digits of the number is " << sum << std::endl;
}
For the sake of readability, it might help to not pass in the charlength into the function, and just do that inside the method. Besides that, a for loop seems like a better option in this case as well.
void calc(string num) {
int sum = 0, int i = 0;
//for loop run from num.length - 1 to 0 {
/*numarray[i] = stoi(num.at(i));*/
/*sum = sum + numarray[i];*/
sum = sum + stoi(num.at(i));
cout << numarray[i] << endl;
i++;
}
cout << sum << endl;
}