-1

I'm writing a simple program that does int division and shows the remainder. I am trying to have the program run continuously until the user inputs 0 0. The program does stop after the user puts 0 0 but not before it says "Floating point exception" every single time. This is the code:

#include <stdio.h>

int main(){

  int x;
  int y;

  while (1){
    if (x && y == 0)
      break;
    else      
    scanf ("%i %i", &x , &y);
    printf("%i %i / %i\n" , x / y , x % y, y);
  }


return 0;

}
BRK
  • 9
  • 3

3 Answers3

1

Your order is incorrect. You are doing it in this order:

  1. Check if we are done (incorrectly, as you need x == 0 && y == 0)
  2. Read user input
  3. Write calculated output

You do not check if you are complete before calculating the output, so the calculation fails first.

Guvante
  • 18,775
  • 1
  • 33
  • 64
0

if (x && y == 0) doesn't do what you think it does. You probably meant if (x == 0 && y == 0).

Also you shouldn't operate on any uninitialized values. Give them appropriate values before using these variables in any expressions, or at least ensure user input is taken before these are applied.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

You need to check for 0 before attempting an operation:

#include <stdio.h>

int main(){

  int x;
  int y;

  while (1){
    scanf ("%i %i", &x , &y);

    if (x == 0 && y == 0)
      break;

    printf("%i %i / %i\n" , x / y , x % y, y);
  }

return 0;

}
Colin Young
  • 3,018
  • 1
  • 22
  • 46
  • Yeah, just edited. Didn't read the full code after seeing the obvious (to me) first error. – Colin Young Feb 05 '15 at 18:26
  • You should - (1) Initialize x and y to some value (zero maybe?). (2) Check the return value of `scanf` to see if the input was successful and both variables were initialized. – Happy Green Kid Naps Feb 05 '15 at 18:29
  • @HappyGreenKidNaps: If you initialized the vars to 0 in the original code it would never have reached the scanf. To be fair, that would have taken care of the floating point exception (even with the faulty comparison I think). – Colin Young Feb 05 '15 at 18:37