【问题标题】:Issues with using if/else statements correctly in C language在 C 语言中正确使用 if/else 语句的问题
【发布时间】:2015-02-06 03:41:26
【问题描述】:

我对编程还是很陌生,所以我不确定要采取的正确措施。当用户选择时,我似乎无法让程序显示不同的选项。要么显示第一个选项,要么显示“无效条目”文本。我只包含问题代码,因为我已经在没有 if/else 语句的情况下测试了其余部分,并且它可以正确计算和显示。

printf("Select interest type: S, Y, M \n\n");
scanf("%ch", &type); /*program has finished calculating and is waiting on user input. Variable 'type' has already been initialized as a char*/

printf("\n\nIn %i years, at %.2f percent interest rate, \n", n, R);

/*this is where the problem starts*/
if (type == 'S')
    printf("Your investment becomes %.2f dollars, with simple interest.\n", futureVal_simp);
else
{
    if (type == 'Y')
        printf("Your investment becomes %.2f dollars, with annual compounding interest.\n", futureVal_yr);
    else
    {
        if (type == 'M')
            printf("Your investment becomes %.2f dollars, with monthly compounding interest.\n\n\n", futureVal_mnth);
        else printf("Invalid entry.\n\n\n"); /*these are supposed to display based on char entered*/
    }
}


return 0;
}

我检查了网站上的其他问题,但仍不确定。我应该使用 != 和 && 而不是多个 if/else 吗?

【问题讨论】:

  • 我很可能会为此使用switch 声明,或者至少使用else if

标签: c if-statement nested


【解决方案1】:

你想要scanf("%c", &type); 而不是"%ch"%c 表示字符,h 表示文字 h

您还需要检查scanf() 的返回值。总是。

【讨论】:

  • 这就是我的想法,但是当我将其更改为 '%c' 时,它根本不要求输入。显然还有其他问题。
  • @Nemorov:那么缓冲区中仍然有一些东西被 %c 消耗,并且对于问题中的代码,scanf 只是等待文字 h。请提供完整的代码示例以及问题中的确切输入。
  • @Nemorov 我已经为您的问题添加了解决方案。作为评论解释太冗长了。我不得不为此添加一个单独的分析器。请尝试一下。
【解决方案2】:

使用逻辑运算符/if-else 语句——如果它们是等价的,选择其中之一就是你的选择。 (也许在这种情况下,您也可以使用 switch 语句。) 但有时,使用过长的逻辑公式作为条件会降低代码的可读性。

if(type == 'S')
{
    content...
}
else if(type == 'Y')
{...}
else if(type == 'M')
{...}
else{...} 

因为 else if 意味着 else{if(...)} 本身,所以你不需要在 else 块中编写另一个 if/else 语句。

我推荐的最好方法是在这种情况下使用 switch 语句。分支条件并不复杂——这些条件只是检查字符“类型”是“S”、“Y”、“M”还是其他。在这种情况下,switch 语句可以增加代码的可读性。

【讨论】:

  • 这是使用 switch/case 的非常好的建议。 char 是整数类型,所有条件都使用 ==。此外,代码将更紧凑且更易于维护。
【解决方案3】:

您已经从 @John Zwinck 先生那里得到了答案,但只是为了完整起见,

你应该改变你的 scanf

 scanf("%ch", &type);

scanf(" %c", &type);  // note the extra space before %c

这告诉scanf() 忽略所有以前的类似空白的字符并读取第一个非空白输入。

仅供参考,在之前的情况下,之前按下的 ENTER 击键 [在之前的输入之后] 被存储为输入缓冲区中的 \n。然后,\n 作为%c有效 输入,正在被scanf() 读取,从而产生场景

'%c' 它根本不要求输入。

另外,作为一种改进,您可以考虑使用 switch 语句代替 if-else 条件。

【讨论】:

  • 如果有人可以让我知道投票背后的原因,我会很高兴。
猜你喜欢
  • 2013-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多