A float x==0 includes values like 0.7. How to change this?

Asked

Viewed 82 times

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");
   }
}
  • 1

    0,5 is not a valid number in C. In most programming languages the decimal separator is the point, so you would have to input 0.5. I believe that the scanf is capturing only the valid part of the 0,5, which in this case would be 0.

1 answer

0

You should use the decimal part separator "." instead of ","

  • 2

    0/4.2 it’s not a mistake!

  • True, I edited the answer, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.