I want to display an error when "/0" is entered on the calculator in C language.

Asked 1 years ago, Updated 1 years ago, 327 views

I have a question about C language.
When I submitted the following code for the calculator problem, I was told to add a code that displays an error when the user enters /0, but I don't know how to do it, so could someone tell me?

#include<stdio.h>
int main() {
    int num1, num2;
    charop;
    float answer;
    intr;
    r = scanf("%d%c%d", & num1, & op, & num2);
    if(r!=3){
        puts("input error");
        return1;
    }
    switch(op){
    case '+':
        answer = num1 + num2;
        break;
    case '-':
        answer = num1-num2;
        break;
    case '*':
        answer = num1 * num2;
        break;
    case '/':
        answer=(float) num1/num2;
        break;
    }
    printf("%f\n", answer);
    return 0;
}

c

2022-11-03 00:01

1 Answers

case '/':
answer=(float) num1/num2;
break;

Add a little more to this code

case '/':
if(num2==0){
  puts("Divid by Zero");
  return1;
}
answer=(float) num1/num2;
break;

How about that?


2022-11-03 00:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.