A
A
Anvario02021-12-28 14:14:42
C++ / C#
Anvario0, 2021-12-28 14:14:42

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;
    }
  }
}


The answer that the program gives is:
r = 102
a = 210
The answer is obviously wrong, because 102 * 2 != 210.
I spent a long time on it, but I still can't figure out what the error is in the code. I would be grateful if you help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-28
@res2001

Because integer division: a / rresults 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 question

Ask a Question

731 491 924 answers to any question