编写一个c语言程序,用switch语句,从键盘输入一个四位整数n,输出它的各位数之和
时间: 2023-04-05 11:05:23 浏览: 106
好的,这个问题可以回答。以下是代码:
```c
#include <stdio.h>
int main() {
int n, sum = 0;
printf("请输入一个四位整数:");
scanf("%d", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("各位数之和为:%d\n", sum);
return 0;
}
```
使用 switch 语句也可以实现,以下是代码:
```c
#include <stdio.h>
int main() {
int n, sum = 0;
printf("请输入一个四位整数:");
scanf("%d", &n);
switch (n / 1000) {
case 1:
sum += 1;
break;
case 2:
sum += 2;
break;
case 3:
sum += 3;
break;
case 4:
sum += 4;
break;
case 5:
sum += 5;
break;
case 6:
sum += 6;
break;
case 7:
sum += 7;
break;
case 8:
sum += 8;
break;
case 9:
sum += 9;
break;
}
switch (n / 100 % 10) {
case 1:
sum += 1;
break;
case 2:
sum += 2;
break;
case 3:
sum += 3;
break;
case 4:
sum += 4;
break;
case 5:
sum += 5;
break;
case 6:
sum += 6;
break;
case 7:
sum += 7;
break;
case 8:
sum += 8;
break;
case 9:
sum += 9;
break;
}
switch (n / 10 % 10) {
case 1:
sum += 1;
break;
case 2:
sum += 2;
break;
case 3:
sum += 3;
break;
case 4:
sum += 4;
break;
case 5:
sum += 5;
break;
case 6:
sum += 6;
break;
case 7:
sum += 7;
break;
case 8:
sum += 8;
break;
case 9:
sum += 9;
break;
}
switch (n % 10) {
case 1:
sum += 1;
break;
case 2:
sum += 2;
break;
case 3:
sum += 3;
break;
case 4:
sum += 4;
break;
case 5:
sum += 5;
break;
case 6:
sum += 6;
break;
case 7:
sum += 7;
break;
case 8:
sum += 8;
break;
case 9:
sum += 9;
break;
}
printf("各位数之和为:%d\n", sum);
return 0;
}
```
阅读全文