【问题标题】:The switch statement is not initializing the value even if the case is True?即使 case 为 True,switch 语句也不会初始化值?
【发布时间】:2020-06-13 14:20:02
【问题描述】:

我希望这个 switch 语句为变量选项初始化正确的值,但它没有初始化,因此不允许 if 语句工作。

#define arti 2.05

int main(void)
{
    char ch;
    float option = 0;

    while(ch = getchar())
    {
        ch = toupper(ch);

        switch(ch)
        {
            case 'A':
                option = arti; //value of arti is 2.05
                break;

            case 'B':
                option = beets;
                break;

            default:
                printf("Enter a valid value.\n");
                continue;
                break;
        }

       if(option == arti)
        {
            printf("arti printed successfully!\n");
        }

    }

    return 0;
}

我得到的输出是这样的:

a //input
Enter a valid value. //output

我不知道问题出在哪里,我已使这段代码尽可能短,以便向您解释问题。请帮我解决这个问题。

【问题讨论】:

  • @AdrianMole 我什至尝试将“A”作为输入仍然无法正常工作。
  • continue; break; 嗯。

标签: c if-statement initialization switch-statement c11


【解决方案1】:

您正在将 float 值 (option) 与 double 常量 (arti) 进行比较,这会导致问题。要将arti 定义为(单精度)float,请添加f 后缀:

#define arti 2.05f

【讨论】:

  • 它的工作原理......直到现在我还不知道......谢谢......
猜你喜欢
  • 2016-05-12
  • 2023-04-07
  • 1970-01-01
  • 2018-01-20
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多