在C语言中正确使用if / else语句的问题

时间:2015-02-06 03:41:26

标签: c if-statement nested

我对编程还很新,所以我不确定要采取的正确行动。当用户选择时,我似乎无法让程序显示不同的选项。显示第一个选项,或显示“无效条目”文本。我只会包含问题代码,因为我在没有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?

3 个答案:

答案 0 :(得分:2)

您希望scanf("%c", &type);不是"%ch"%c表示字符,h表示字面h

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

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:0)

你已经得到了 @John Zwinck 先生的答案,但仅仅是为了完整,

您应该从

更改您的scanf
 scanf("%ch", &type);

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

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

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

  

'%C'它根本不会要求输入。

此外,作为改进,您可以考虑使用switch语句而不是if-else条件。