Answer the question
In order to leave comments, you need to log in
What causes a C program to give the wrong answer?
Task: Some natural number ends in two. If it is rearranged to the first place, then the number will double. What was the minimum number originally?
#include <stdio.h>
int main() {
int a = 1;
int proverka = 0;
while (1)
{
if (a % 10 == 2) {
int r = a; //Сохраняем начально значение a
int x = a;
int count = 0;
while (x > 0) {
x /= 10;
count += 1; //Считаем, сколько у числа разрядов
}
a /= 10;
a = a + 2 * pow(10, (count - 1));
if (a / r == 2) {
printf("r = %d\n", r);
printf("a = %d\n\n", a);
proverka = 1;
}
a = r;
}
a++;
if (proverka == 1) {
break;
}
}
}
Answer the question
In order to leave comments, you need to log in
Because integer division: a / r
results in 2 without a remainder. You need to convert to floating point numbers, perform floating point division, and get the remainder with modf.
A couple more notes:
1. Obviously, your algorithm starts with 12, because this is the first number with more than 1 digit in the composition, in which the lowest digit is 2. So everything that is less than 12 makes no sense to sort through.
2. It makes no sense to increase a by 1 - increase immediately by 10, i.e. to the next option with a deuce at the end, why go through the options that you miss. In addition, in this case, count can not be calculated as you are doing now, but simply add 1 every 10 iterations.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question