C 为什么要打印;应付款2“;而它应该是;应付款0“;

C 为什么要打印;应付款2“;而它应该是;应付款0“;,c,C,我制作了一个名为juice的函数,让客户选择杯子的大小 他们的juice并返回价格或应付金额,但是当我选择switch语句的默认情况时,它应该返回0,但输出是2 #include <stdio.h> int juice(char size , int qty){ int price =0; switch(size){ //'s' for small size of cup case 's': printf("size small");

我制作了一个名为juice的函数,让客户选择杯子的大小 他们的juice并返回价格或应付金额,但是当我选择switch语句的默认情况时,它应该返回0,但输出是2

#include <stdio.h>

int juice(char size , int qty){
int price =0;
switch(size){
    //'s' for small size of cup
    case 's':
        printf("size small");
        price =20*qty;
        return price; 
        break;
    //'m' for medium size of cup
    case 'm':
        printf("size medium");
        price =30*qty;
        return price;
        break;
    //'l' for large size of cup
    case 'l':
        printf("size large");
        price =40*qty;
        return price;
        break;
    //if costumer choose wrong size
    default:
        printf("choose proper size");
    }

printf("\n%d", price);
}

int main()
{
    int price =juice('d' ,5);
    printf("\npayable is  %i\n", price);
    return 0;
}

问题是函数在
默认情况下没有返回。这是未定义的行为

注意
退货价格使以下
中断是不必要的,而且它也使代码更难阅读,相反,由于您在每种情况下都设置了
价格
的值(除了
默认值
),因此您只需输入
退货价格在末尾。最后,在
default
案例中添加一条初始化语句

像这样的

int juice(char size, int qty)
{
    int price = 0;
    switch (size) {
        case 's': // 's' for small size of cup
            printf("size small\n");
            price = 20 * qty; 
            break;
        case 'm': // 'm' for medium size of cup
            printf("size medium\n");
            price = 30 * qty;
            break;
        case 'l': // 'l' for large size of cup
            printf("size large\n");
            price = 40 * qty;
            break;
        default: // if costumer choose wrong size
            printf("choose proper size\n");
            price = -1; // Invalid value?
            break;
    }
    return price;
}

另外,新行字符
'\n'
要放在一行的末尾,IO流是行缓冲的,这样可以刷新流并创建新行,将字符放在末尾更为合理。

大小
不是有效的选择时,您不会返回任何内容,这意味着
price
可能是一个垃圾值。在函数末尾明确返回
0
。(在
return
之后,您不需要“中断”开关--
break
无法到达,因为您已从函数返回。)但我认为垃圾值不应该每次编译时都相同,但事实确实如此。@ShivamSingh:未定义行为的奇妙之处在于,它可以是一致的,也可以是不一致的,而您的代码仍然是错误的,结果仍然是正确的,因为所需的结果是未定义的。@ShivamSingh,这就是未定义行为,似乎没有人理解。原则上它是可预测的,但不是来自代码本身。请注意,计算机程序是确定性的,因此,除非您更改影响生成程序的某些内容,否则这些内容不会更改。您不能故意更改这些内容,您不知道到底是什么触发了更改。未定义的行为就是,未定义。在你编译了一千次修改的程序后,它的行为是否相同并不重要,它仍然是未定义的行为。
int juice(char size, int qty)
{
    int price = 0;
    switch (size) {
        case 's': // 's' for small size of cup
            printf("size small\n");
            price = 20 * qty; 
            break;
        case 'm': // 'm' for medium size of cup
            printf("size medium\n");
            price = 30 * qty;
            break;
        case 'l': // 'l' for large size of cup
            printf("size large\n");
            price = 40 * qty;
            break;
        default: // if costumer choose wrong size
            printf("choose proper size\n");
            price = -1; // Invalid value?
            break;
    }
    return price;
}