选择结构
一.if-else选择结构
1
if (grade>=90)
printf("A");
else if (grade>=80)
printf("B");
else if (grade>=70)
printf("C");
else if (grade>=60)
printf("D");
else
printf("E");
2.条件运算符:? :
• 当 a=3, b=2 时,a>b ? a+b : a-b 的值为 a+b,即 5;
• 当 a=2, b=3 时,表达式的值为 a-b,即 -1
例:闰年的判断
void main() { int year, bleap = 0; printf("please input the year: "); scanf("%d", &year); if(year % 100 != 0) { if(year % 4 == 0) bleap = 1; } else if(year % 400 == 0) bleap = 1; bleap ? printf("%d is a leap year!", year) : printf("%d is not a leap year!", year); }
or
void main() { int year; printf("please input the year: "); scanf("%d", &year); if((year % 100 != 0 && year % 4 == 0) || year % 400 == 0) printf("%d is a leap year!", year); else printf ("%d is not a leap year!", year); }
二.switch-case选择结构
grade=getchar();
switch(grade)
{
case 'A': printf("85~100\n");
case 'B': printf("70~84\n");
case 'C': printf("60~69\n");
case 'D': printf("<60\n");
default: printf("error\n");
}
例:任意输入两个数,和一个运算符,输出运算结果
void main() { int op1, op2, oprtr; scanf("%d%d", &op1, &op2); oprtr=getchar(); switch(oprtr) { case '+': printf("=%d", op1+op2); break; case '-': printf("=%d", op1-op2); break; case '*': printf("=%d", op1*op2); break; case '/': printf("=%d", op1/op2); break; default: printf("operator is invalid!"); } }
void main() { int op1, op2, oprtr, result, done=1; scanf("%d%d", &op1, &op2); operator=getchar(); switch(oprtr) { case '+': result=op1+op2; break; case '-': result=op1-op2; break; case '*': result=op1*op2; break; case '/': result=op1/op2; break; default: done=0; } if (done) printf("%d%c%d=%d", op1, oprtr, op2, result); else printf("operator is invalid!"); }
例:根据输入的月份,给出当月的天数
void main() { int m, d; scanf("%d", &m); switch (m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: d=31; break; case 4: case 6: case 9: case 11: d=30; break; case 2: d=28; break; default: d=0; } d > 0 ? printf("%d", d) : printf("invalid input!"); }

浙公网安备 33010602011771号