1 #include <stdio.h> 2 void main(void) 3 { 4 char ch; 5 printf("请输入一个字符:"); 6 ch = getchar();/*getchar、putchar专门用于字符输入输出; 7 getchar()写法上要写为 变量 = getchar(); 8 putchar()用法为putchar(变量); 9 putchar('\n')输出一个控制符; 10 putchar('字母/字符');输出字母/字符; 11 */ 12 if(ch<=31) 13 { 14 printf("这是一个控制字符或通讯专用字符!\n"); 15 } 16 else if(ch >= '0' && ch <= '9') 17 { 18 printf("这是一个数字!\n"); 19 } 20 else if(ch >= 'A' && ch <= 'Z') 21 { 22 printf("这是一个大写字母!\n"); 23 } 24 else if(ch >= 'a' && ch <= 'z') 25 { 26 printf("这是一个小写字母!\n"); 27 } 28 else 29 { 30 printf("这是其他字符!\n"); 31 } 32 } 33 return 0;
以上是一段用于判断字符的程序,也是if-else的典型例题。
下面是swtich的句式结构
switch(表达式)
{
case 常量1:语句1;
case 常量2:语句2;
…
case 常量n:语句n;
default: 语句n+1;
}
例如:
#include <stdio.h> void main(void) { double a,b; char ch; printf("Input a(+ - * /)b:"); scanf("%f%c%f",&a,&ch,&b); switch(ch) { case '+': printf("%f%c%f=%.2f\n",a,ch,b,a+b);/*%.2f表示精度,可以理解为保留两位小数*/ break; case '-': printf("%f%c%f=%.2f\n",a,ch,b,a-b); break; case '*': case 'X': case 'x': printf("%f%c%f=%.2f\n",a,ch,b,a*b);/*输入"x" "X" "*" 都执行这一条语句;不加break,会顺语句执行*/ break; case '/': printf("%f%c%f=%.2f\n",a,ch,b,a/b); break; default: printf("请输入正确算式!\n"); } return 0; }
再例如:
#include <stdio.h> int main(void) { unsigned age; printf("Please enter your age(old years):"); int result = scanf_s("%3d", &age); if (result == 0) { printf("Your age is wrong,please enter your correct age!\n"); return 0; } switch (age) { case 18: printf("Congratulate!You are an adult.\n"); break; case 22: printf("Congratulate!You can marry somebody.\n"); break; case 60: printf("Congratulate!You are retired.\n"); break; default: printf("Sorry,there aren't your age.\n"); break; } printf("Thank you for your participatation!"); return 0; }
标签:case,sixteenth,ch,age,else,break,语句,2023.1,printf From: https://www.cnblogs.com/ningzj/p/17035351.html