[英]When exactly do we use “if else-if” and “case break” statements in C language? I wrote 2 codes for a problem, but the difference I don't understand
我希望根據我的代碼理解問題問題,
這是我使用 case-break 語句編寫的代碼:
#include<stdio.h>
int main()
{
int x;
printf("Pick an integer from 1, 2 and 3: ");
scanf("%d", &x);
switch(x)
{
case 1:
printf("1 is a unique number.\n", x);
break;
case 2:
printf("2 is the smallest and the only even prime number.\n", x);
break;
case 3:
printf("3 is the first odd prime number.\n", x);
break;
default:
printf("I haven't even asked you to enter %d\n", x);
}
return 0;
}
這是我使用 if else-if 語句編寫的代碼:
#include<stdio.h>
int main()
{
int input;
printf("Enter any one of 1, 2, and 3 ");
scanf("%d", &input);
if(input==1)
printf("%d is a unique number", input);
else if(input==2)
printf("%d is the only even prime number", input);
else if(input==3)
printf("%d is the smallest odd prime number", input);
else
printf("I did not even ask you to enter %d", input);
return 0;
}
謝謝你
如果您要檢查同一變量的不同值,則由您決定使用 switch() 還是 if()
如果您正在檢查 2 個或更多變量的值(甚至可能是它們的組合),那么您最好使用 else if()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.