首页 > 解决方案 > 我的 C 代码有问题。它返回非零值,我不知道为什么

问题描述

我试图弄清楚为什么以及如何返回到非零值?

结构如下:

询问用户喜欢什么 -> 咖啡或茶 -> 如果咖啡/茶 -> 多少杯 -> 0-3/3-20 -> printf's

否则,如果用户没有给出正确的答案-> else'error'。

这是我学校的作业。

#include <stdio.h>

int main()
{
    char coff = 'c', tea = 't', answer;
    int x = 0;
    printf("Do you drink coffee or tea(c/t)?");
    scanf("%c", &answer);
    if((answer == 'c') || (answer =='t'))
    {
            printf("How many cups do you drink daily:");
            scanf("%d", &x);
        
        if(answer =='c' && x<=2)
        {
            printf("You don't drink a lot of coffee, do you?");
        }
        if(answer == 'c' && x>3)
        {
            printf("You drink a lot of coffee!");
        }
        if(answer =='t' && x<=2)
        {
            printf("You do not drink a lot of tea.");
        }
        if(answer =='t' && x>3)
        {
            printf("You drink a lot of tea!");
        }
    }
        else
            printf("An error occurred in the program!");

    return 0;
}

标签: c

解决方案


考试:

if(answer == 'c' && x>3)

应该是以下之一:

if( answer == 'c' && x >= 3 )

或者

if( answer == 'c' && x > 2 )

因为 3 既不大于 3 也不小于或等于 2。

无论如何,值得您使解决方案过于复杂;它充满了对您已经知道为真的条件的重复测试,以及由于先前的条件为假而对您已经知道为真的事物进行测试。你可以做什么(一个天真的改进):

    if(answer =='c' )
    {
        if( x < 3 )
        {
            printf("You don't drink a lot of coffee, do you?");
        }
        else
        {
            printf("You drink a lot of coffee!");
        }
    }
    else
    {
        if( x < 3 )
        {
            printf("You don't drink a lot of tea, do you?");
        }
        else
        {
            printf("You drink a lot of tea!");
        }
    }

我可能会做什么:

    if( x < 3 )
    {
        printf( "You don't drink a lot of %s, do you?", 
                answer == 'c' ? "coffee" : "tea" ) ;
    }
    else
    {
        printf("You drink a lot of %s!", 
                answer == 'c' ? "coffee" : "tea" ) ;
    }

推荐阅读