c语言编程例题PTA
时间: 2025-04-18 20:24:54 浏览: 30
### C语言编程例题及解答
#### 使用PTA平台进行C语言编程练习
PTA程序设计类实验辅助教学平台是一个在线编程平台,旨在为学生提供良好的编程实践环境,帮助学生掌握编程语言和编程思想,提高程序设计能力。该平台提供了丰富的编程练习题目和实验题目,学生可以在线编辑代码并提交解答,平台会自动判断答案的正确性并给出反馈[^1]。
下面展示几个常见的C语言编程实例及其解决方案:
#### 实现投票统计功能
```c
#include <stdio.h>
#include <string.h>
int main() {
char votes[] = "ABCAACBB";
int count[256] = {0};
for (int i = 0; i < strlen(votes); ++i) {
count[votes[i]]++;
}
printf("Vote statistics:\n");
for (char ch = 'A'; ch <= 'Z'; ++ch) {
if (count[ch]) {
printf("%c : %d\n", ch, count[ch]);
}
}
return 0;
}
```
这段代码实现了简单的投票统计功能,通过遍历字符数组`votes`来计算每个字母出现次数,并输出结果[^2]。
#### 判断某一年是否为闰年
```c
#include <stdbool.h>
#include <stdio.h>
bool isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
int main() {
int year;
scanf("%d", &year);
if (isLeapYear(year)) {
printf("%d 是闰年。\n", year);
} else {
printf("%d 不是闰年。\n", year);
}
return 0;
}
```
此段代码定义了一个名为`isLeapYear()`的函数用来判定给定的一年是不是闰年,并在主函数中调用了这个函数来进行具体测试。
#### 打印杨辉三角形
```c
#include <stdio.h>
void printPascalTriangle(int nRows) {
long pascalValue = 1;
for (int line = 0; line < nRows; ++line) {
for (int space = 0; space < nRows - line - 1; ++space) {
printf(" ");
}
for (int col = 0; col <= line; ++col) {
printf("%ld ", pascalValue);
pascalValue = pascalValue * (line - col) / (col + 1);
}
printf("\n");
pascalValue = 1;
}
}
int main() {
int rows;
scanf("%d", &rows);
printPascalTriangle(rows);
return 0;
}
```
上述代码展示了如何构建以及打印指定行数的杨辉三角形,其中利用了组合数学中的性质简化了计算过程。
阅读全文
相关推荐

















