質問

if (num2 != 0)
    printf("\nInput 3 / Input 2 (int)    %12d", divide);
else if (num2 == 0)
    printf("\nInput 3 / Input 2 (int)    DIV/0");


if (flt4 != 0)
    printf("\nInput 2 / Input 1 (double) %16.3f", divide2);
else if (flt4 == 0)
    printf("\nInput 2 / Input 1 (double)    DIV/0");

When I set num2 or flt4 equal to 0 the program crashes. Otherwise it works perfectly fine. I was looking over the reading about if/else statements and I believe my formatting is correct, but there is obviously an error.

Thanks.

EDIT:

The code where i define divide is:

void calculate (int num1, int num2, int num3, float flt4,int* sum,int* mult,
            int* mod,int* divide,double* mult2,double* divide2)
{

*sum = num1 + flt4;
*mult = num1 * num3;
*mod = (num1/10)%10;
*divide= num3 / num2;
*mult2= num1 * flt4;
*divide2= (double)num2 / num1;
return;
}

My question then is, how do I structure this program so if it divides by zero I can display that in the print function.

役に立ちましたか?

解決

Most likely you are dividing by zero. The divide variable is set before the 'if' and you perform that operation anyway. Put that inside the first 'if', so it will divide by the num2 iff num2 is different than zero.

Edit: It should look like that:

if (num2 != 0) {
    divide = something / num2;
    printf("\nInput 3 / Input 2 (int)    %12d", divide);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top