Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
Why the usage of floating point numbers in switch doesn't worky?

picture shows the code with error while using switch

#include <stdio.h>

int main() {
    int a = 1.0;

    switch (a) {
      case 1:
        printf ("1");
        break;

      case 1.0:
        printf ("10");
        break;

      default:
        printf ("default");
    }
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Because switch depends on exact, plain-data comparison.

Comparisons between floats probably don't work as you expect them to, for example, there's a negative and a positive zero.

See: Is floating point math broken?

For these reasons, you can't "simply" say "a == b" when you mean that, as a human. That's why the C standard simply doesn't allow it as a case in a switch.

Truth is: the fact that you're trying to do that is a good reason for forbidding it! Either you're using floats where you shouldn't (namely, to store a limited set of discrete values), or you haven't really understood how floats work, and using them in a switch statement will lead to unexpected behaviour.

over 4 years ago · Santiago Trujillo Report

0

As for the "Please help me" part of your question, you can probably implement that more-or-less as follows...

rather than

double x=1.,y=2.;
blah; blah; blah;
switch(x){
  default: break;
  case y: blah; break;
  }

try instead something like

double x=1., y=2., xmax=10000., xmin=1.;
int   ix=1, iy=2,  imax=100;
blah; blah; blah;
ix = ((x-xmin)/(xmax-xmin))*((double)imax);
iy = ((y-xmin)/(xmax-xmin))*((double)imax);
switch(ix){
  default: break;
  case iy: blah; break;
  }
over 4 years ago · Santiago Trujillo Report

0

why can't we use floating point numbers in switch conditional statements?

  1. Because the language definition says so.

  2. Because comparing floating-point numbers for exact equality (which a switch statement implicitly does) is often a bad idea.

  3. Because using floating-point variables as control variables is usually a bad idea. @Steve Summit

  4. No compelling need for this feature.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!