Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda