1
Hello! I’m new to the programming world and I’m making a small calculator. I made an if that terminates the program if the user tries to divide by 0, but when I try to divide by for example 0.5 the program enters this if and says that I can’t divide anything by 0. How to fix? Thank you!
#include <cstdlib>
#include <locale.h>
#include <cstdio>
int main()
{
setlocale(LC_ALL, "");
float num1, num2;
int op;
printf("Hi there! Welcome to the best calculator ever! Choose the first number\n");
scanf("%f", &num1);
printf("Great! Now, choose what operation you want to execute: 1-Adition 2-Subtraction 3-Multiplication 4-Division\n");
scanf("%d", &op);
while (op > 4 || op < 1) {
printf("This is not an option. Choose another one\n");
scanf("%d", &op);
}
printf("Almost there! Choose the second number!\n");
scanf("%f", &num2);
if (op == 1) {
printf("Addition = %.3f \n", num1+num2);
system("pause");
}
else if (op == 2) {
printf("Subtraction = %.3f \n", num1-num2);
system("pause");
}
else if(op == 3) {
printf("Multiplication = %.3f \n", num1*num2);
system("pause");
}
else if(op == 4 && num2 == 0) {
printf("You can't divide anything by zero...I thought you knew better, son. \n");
system("pause");
}
else if(op == 4) {
printf("Division = %.3f \n", num1/num2);
system("pause");
}
}
0,5
is not a valid number inC
. In most programming languages the decimal separator is the point, so you would have to input0.5
. I believe that thescanf
is capturing only the valid part of the0,5
, which in this case would be 0.– Andre