简体   繁体   English

在 switch 条件下使用浮点数不起作用,为什么?

[英]Usage of floating point numbers in switch condition doesn't work, why?

For better understanding I have added screeshot.为了更好地理解,我添加了截图。 It is giving the error, case label doesn't reduce to an integer constant.它给出了错误,案例标签不会减少为整数常量。 What does it mean?这是什么意思? 图为使用开关时出错的代码

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

Because switch depends on exact , plain-data comparison.因为switch依赖于精确的、纯数据的比较。

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.由于这些原因,作为一个人,当你的意思是说“a == b”时,你不能“简单地”说“a == b”。 That's why the C standard simply doesn't allow it as a case in a switch .这就是为什么 C 标准根本不允许它作为switch中的case

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.要么你在不应该使用浮点数(即,存储一组有限的离散值),要么你还没有真正理解浮点数是如何工作的,在switch语句中使用它们会导致意外行为。

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;
  }

why can't we use floating point numbers in switch conditional statements?为什么我们不能在 switch 条件语句中使用浮点数?

  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.因为比较浮点数是否完全相等(switch 语句隐含地这样做)通常是一个坏主意。

  3. Because using floating-point variables as control variables is usually a bad idea.因为使用浮点变量作为控制变量通常是个坏主意。 @Steve Summit @史蒂夫峰会

  4. No compelling need for this feature.没有迫切需要此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM