酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

编写c程序,实现某托儿所收2到6岁的孩子,2岁、3岁孩子进小班(lower class);4岁孩子进中班(middle class);5岁、6岁孩子进大班(higher class) 编写程序(用switch 语句),输入孩子年龄,输出年龄及进入的班级号。如:输入3,输出:age:3,enter lower class。(要求代码防止输入错误)

以下是使用 C 语言编写的解决此问题的程序: ```c #include <stdio.h> int main() { int age; printf("Please enter the age of the child: "); if (scanf("%d", &age)!= 1) { printf("Invalid input. Please enter a valid age.\n"); return 1; } if (age < 2 || age > 6) { printf("Invalid age. The age should be between 2 and 6.\n"); return 1; } switch (age) { case 2: case 3: printf("age: %d, enter lower class\n", age); break; case 4: printf("age: %d, enter middle class\n", age); break; case 5: case 6: printf("age: %d, enter higher class\n", age); break; } return 0; } ``` 在这个程序中,首先使用`scanf`函数获取用户输入的年龄。如果输入的不是整数,会提示输入无效。然后检查年龄是否在有效范围内(2 到 6 岁),如果不在,也会提示无效。最后使用`switch`语句根据年龄输出对应的班级信息。 [2024-11-04 16:33:11 | AI写代码神器 | 308点数解答]

相关提问