0

it's my first question on here, so I have to make program to run the euclidean algorithm, and this is the result:

printf("Bitte geben Sie eine Zahl ein: ");
scanf("%d\n", &a);
printf("Bitte geben Sie eine zweite Zahl ein: ");
scanf("%d\n", &b);

do
{
    r = a % b;
    a = (a / b) + r;
    a = b;
    b = r;
    g = a;
} while (b != 0);

printf("Der groesste gemeinsame Teiler ist: %d\n", g);

The problem is that when I run the code, it goes like this:


printf("message")->scanf("&a")->scanf("&b")->printf("message")->scanf(doesn't matter)->printf("result")


But it's supposed to go like:


printf("message")->scanf("&a")->printf("message")->scanf("&b")->printf("result")


The algorithm works, but it's the input that is completely jacked, am I doing something wrong or could it be the compiler? I use msys2 gcc mingw64. Appreciate your help already!

basmi
  • 1
  • 2
    Remove the `\n` from your `scanf`s. Also you might need to add `\n` to your `printf`s or add `fflush(stdout);` after each because of line buffering. – Eugene Sh. Apr 30 '21 at 14:01
  • Your description is unclear. Please explain what the user of the program sees, in terms of "I type this", "the computer writes that". – n. m. could be an AI Apr 30 '21 at 14:02
  • @EugeneSh. You sir are my hero, removing \n in the scanf() operator worked like a charm! Thank you! – basmi Apr 30 '21 at 14:07
  • @basmi `printf` only puts the message into the stdout buffer, that buffer is occasionally flushed to the console screen. This allows a lot of little `printf` statements to build up a single line without tying up the Operating System in transferring the information between the "display screen" and your running program. To force a flush of the buffer, put `fflush(stdout)` after each `printf` where you want to ensure the message is displayed; or. use a variant of `scanf` that also displays a message (where they will handle the `printf` and `fflush` for you) – Edwin Buck Apr 30 '21 at 14:34
  • Just as a side note: It is unsafe to use `scanf` without checking the return value. See this page for further information: [A beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) – Andreas Wenzel Apr 30 '21 at 19:55

0 Answers0