C语言统计数据文件特定范围末位数字为6的个数
C语言统计数据文件特定范围末位数字为6的个数
假设数据文件为'data.txt',以下是一种可能的解决方案:
#include <stdio.h>
int main() {
FILE *fp;
int num, count = 0;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
for (int i = 1; i <= 1000; i++) {
fscanf(fp, "%d", &num);
if (i >= 51 && i <= 1000 && num % 10 == 6) {
count++;
}
}
printf("The number of data with last digit 6 between 51 and 1000 is %d.\n", count);
fclose(fp);
return 0;
}
解释:
- 打开数据文件,并检查是否成功打开。
- 用循环读取所有数据,每读取一个数据,判断它是否在指定范围内(即第51到第1000个数据),且末位数字是否为6。如果符合条件,计数器加1。
- 输出计数器的值,即末位数字为6的数据个数。
- 关闭文件,程序结束。
需要注意的是,上述代码假设数据文件中每行只有一个整数,且数据文件已经存在。如果数据文件格式不同或需要用户输入数据文件名,则需要做出相应的修改。
原文地址: https://www.cveoy.top/t/topic/nuYw 著作权归作者所有。请勿转载和采集!