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.
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'm in an introductory c++ course, and am having trouble with this prompt:
"Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by exactly one space. Declare any variables that are needed."
My solution is as follows:
int num = 0;
int evens = 0;
int odds = 0;
int evenSum = 0;
int oddSum = 0;
do {
cin >> num;
if (num % 2 == 0){
evens++;
evenSum += num;
}
else if (num > 0) {
odds++;
oddSum += num;
}
else {
num = -1;
}
}
while (num >= 0);
cout << evenSum << " " << oddSum << " " << evens << " " << odds;
I get no feedback except "Failure: code goes into infinite loop" from the autograder. What am I doing wrong?
You are also processing negative numbers in this if (num % 2 == 0) part(example: this condition when encountered for first negative integer will also be true e.g -6), thereby incrementing evens and adding this negative number to evenSum, which shoudln't have been done as per your question's requirement; Other thing is that the else part is not necessary, I mean why assign -1 to num instead letting it stay the same number you just read(as it is not in your question's requirement).
I think your else if and else part needs to be changed like this:
#include <iostream>
using namespace std;
int main(){
int num;
int evens = 0;
int odds = 0;
int evenSum = 0;
int oddSum = 0;
while (true) {
cin >> num;
if (num < 0){
break;
}
if (num % 2 == 0){
evens++;
evenSum += num;
}
else {
odds++;
oddSum += num;
}
}
cout << evenSum << " " << oddSum << " " << evens << " " << odds;
return 0;
}
Keep taking the numbers from input, if num < 0 then break and show the results, else check for the number being either odd or even and increment the counters accordingly.
You never make num positive in your loop. All your doing is changing other variables. Also you don't need to reassign num to -1 if it's already negative.
You need to add this:
else if (num > 0) {
odds++;
oddSum += num;
num = 1; //becomes positive and breaks the loop.
}
The while part of your loop will keep going until a negative answer is put in. Where are you getting your num from? User input? Your declaration has made it 0, which is making your while loop continue since the condition is >=. If you want user input there should be a cout statement proceeding your cin.
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;
}
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. ;-)