[英]Data loss occurred while counting the number of text files in C
我尝试制作 function 以从文本文件中获取数字并计算不重叠且超过特定数字的数字。 我要把它放在链表中。 计算一个与创建链表不重叠的数字是一件好事,但是计算超过某个数字的数字就有问题了。 它比原来的数字少。 在 Excel 中,有一些数字应该出来,但在我制作的 C 程序 function 的情况下,它们小于那个数字。
void GetData(headNode* rheadnode)
{
int dataType;
int newData;
FILE* fp = NULL;
fp = fopen("input.txt", "r");
if (fp != NULL) {
while (fscanf(fp, "%d", &newData) != EOF)
{
dataType = InsertNode(rheadnode, newData);
if (newData > 5000)
Data_morethan5000_Count++;
switch (dataType)
{
case 0:
break;
case 1:
NodeCount++;
}
}
fclose(fp);
}
}
上面的代码是整个程序代码的一部分。 我正在使用一种方法从input.txt文件中获取一个数字,将其放入newData变量中,如果超过5000则增加Data_morethan5000_Count的值。所以结果应该是45460。但是,C程序输出了一个结果值 45432。我想知道数据丢失发生在哪里。 以下是整个代码。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int key;
struct Node* link;
} listNode;
typedef struct Head {
struct Node* head;
}headNode;
int NodeCount = 0;
int Data_morethan5000_Count = 0;
headNode* initialize(headNode* rheadnode);
int DeleteList(headNode* rheadnode);
void GetData(headNode* rheadnode);
int InsertNode(headNode* rheadnode, int key);
void PrintResult(headNode* rheadnode);
int main()
{
int key;
headNode* headnode = NULL;
headnode = initialize(headnode);
GetData(headnode);
PrintResult(headnode);
DeleteList(headnode);
return 0;
}
headNode* initialize(headNode* rheadnode) {
headNode* temp = (headNode*)malloc(sizeof(headNode));
temp->head = NULL;
return temp;
}
int DeleteList(headNode* rheadnode) {
listNode* p = rheadnode->head;
listNode* prev = NULL;
while (p != NULL) {
prev = p;
p = p->link;
free(prev);
}
free(rheadnode);
return 0;
}
void GetData(headNode* rheadnode)
{
int dataType;
int newData;
FILE* fp = NULL;
fp = fopen("input.txt", "r");
if (fp != NULL) {
while (fscanf(fp, "%d", &newData) != EOF)
{
dataType = InsertNode(rheadnode, newData);
if (newData > 5000)
Data_morethan5000_Count++;
switch (dataType)
{
case 0:
break;
case 1:
NodeCount++;
}
}
fclose(fp);
}
}
int InsertNode(headNode* rheadnode, int key) {
listNode* search, * previous;
listNode* node = (listNode*)malloc(sizeof(listNode));
node->key = key;
search = rheadnode->head;
previous = NULL;
while (search != NULL)
{
if (node->key < search->key)
{
previous = search;
search = search->link;
}
else if (node->key == search->key)
return 0;
else
break;
}
if (previous == NULL)
{
node->link = rheadnode->head;
rheadnode->head = node;
}
else
{
node->link = search;
previous->link = node;
}
return 1;
}
void PrintResult(headNode* rheadnode) {
/*
The total number of nodes: 10011
More than 5000 values: 45460
Execution time: 1.234567 sec
*/
printf("The total number of nodes: %d\n", NodeCount);
printf("More than 5000 values: %d\n", Data_morethan5000_Count);
printf("Execution time: sec");
}
关于:我想知道数据丢失发生在哪里。
没有数据丢失。 相反,有一些重复的数据(键)值。
当有重复时,节点数不增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.