arrays - 计算文件中的重复数字
问题描述
所以我有这个文件myFile.txt,其中包含以下数字:1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1
. 0
我正在尝试编写一个程序来计算一个数字从到重复多少次9
,所以它会像这样打印出来Number %d repeats %d times
。现在我坚持打印出该文件的 n 个元素,例如,如果我想计算前 15 个数字重复自己的次数,首先我会打印出这 15 个数字,然后是数字每个数字重复的次数。但是当我试图打印出这 15 个数字时,它会打印出这个:7914880640-10419997104210821064219560-1975428800327666414848
.
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == '\n'))
count = count + 1;
}
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
解决方案
这就是最终的解决方案。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='\n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("\nNumber %d was found %d times\n", a[i], eval);
}
}
}
return 0;
}
推荐阅读
- java - java.time.Period.between() 在处理不同长度的月份时使用的算法?
- html - 将 html 文件重定向到 localhost 的 8080 端口
- excel - 为什么 IsEmpty(Target) 不能在 VBA 中处理我的 Worksheet_Change() 子?
- terraform - 如何将 terraform 状态集成到 github 操作工作流程中?
- smtp - SMTP 是否传输 7 位或 8 位字符(是否清除 MSB?)
- git - 如何在 Intellij 中配置“更新项目”以从上游存储库中提取并推送到分支?
- c - 无法将大小扫描到数组中
- django - 一个视图中的 Django-allauth 登录/注册
- javascript - 我将如何在 readline-sync 中键入一个字符来执行特定任务?(Node.js)
- wordpress - 有没有办法将变量传递到 WordPress 中的自定义休息路线?