Reputation: 65
I'm writing a program that asks the user to input a three digit number then adds each number by 6 with a modulus of 10.
For example if I enter 619, the output I shall receive is 275.
My only problem is when I enter 100, I receive 1360, instead of 766 like I'm supposed to.
Here is what I have so far:
int main()
{
//declaring variables
int numbers, newNumbers, input;
int newInput = 0;
//User input
printf("Enter a three-digit number: ");
//reads input (%d) and stores it as "input" (&input)
scanf("%d", &input);
//check if input is 3 digits. If not, print message
if(input < 100 || input > 999)
{
printf("Invalid input, the number must be between 100 and 999 \n");
return 0;
}
//loops program until input is 0
while(input > 0)
{
//modulus 10
numbers = input % 10;
//adds 6 to input. Modulus 10
newNumbers = (numbers + 6) % 10;
//if input > 10, calculates new input
if(input > 100)
newInput = newNumbers;
else if(input > 10)
newInput = (newNumbers * 10) + newInput;
else
newInput = (newNumbers * 100) + newInput;
input /= 10;
}
//prints result
printf("Output: %d \n", newInput);
return 0;
}
Upvotes: 1
Views: 98
Reputation: 43
Hi an easier solution is just this one:
output = (input + 666) % 1000; //Add 6 to all numbers
if(input % 10 > 3) //Correct units carry
output-=10;
if(input % 100 > 30) //Correct tents carry
output-= 100;
It works and is easy scalable :)
Upvotes: 0
Reputation: 134286
In your code, by saying
if(input > 100)
newInput = newNumbers;
else if(input > 10)
newInput = (newNumbers * 10) + newInput;
you're not taking into account the numbers 100
and 10
themselves in the TRUE condition, whereas you should be counting them, too. You need to change the if
condition to use >=
, like
if(input >= 100)
newInput = newNumbers;
else if(input >= 10)
newInput = (newNumbers * 10) + newInput;
Upvotes: 2