私はjuiceという名前の関数を作成しました。顧客は のジュースのカップサイズを選択して価格や支払い金額を返しますが、私はそれが0を返す必要がありますswitchステートメントのデフォルトケースを選択するが、出力は2なぜ "Payable 0"であるべきか "Payable 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;
}
出力です:
choose proper size
0
payble is 2
'size'が有効な選択肢でないときは、何も返しません。つまり、' price'はおそらくガベージ値になります。関数の最後に明示的に '0'を返します。 (そして、あなたが 'return'の後にスイッチからブレークアウトする必要はありません - あなたが関数から戻ってきたので、' break'に到達することはできません。) –