lundi 26 mars 2018

The if condition is set to true even it is not necessarily so.

I am trying to learn a little of C programming and I was working this little book that gives me some exercises at the end of each chapter. So here I have this little exercise: "Write a program that accepts two integer values typed in by the user. Display the result of dividing the first integer by the second, to three-decimal-place accuracy. Remember to have the program check for division by zero."

and I wrote this code:

#include <stdio.h>

    int main (void)
    {
        int a, b;
        float c;

        printf ("Type in your number.\n");
        scanf ("%i %i", &a, &b);

        if ( b == 0 )
            printf ("Division by zero!\n");
        else
        {
            c = (float) a / b; 
            printf ("The division of %i and %i is %.3f", a, b, c);
        }

        return 0; 
    }    

all well and good. But I wanted to go a little further, I had in mind to display an appropriate text "Unkown value" or something like that if other than int is typed in. So I first tried to insert a letter for a value and it displayed the same "Division by zero!" message. Now I am wondering why. And on the other hand, can someone give me a little tip how to make the code so it will display "Unkown value" when I type a value other than int and other than 0.

Hope I made myself understood.

Cheers.

Aucun commentaire:

Enregistrer un commentaire