我尝试使函数从文本文件中获取数字并计算不重叠且超过特定数字的数字。我将其放在链接列表中。计算与创建链表不重叠的数字是一件好事,但是对超过一定数字的数字进行计数存在问题。出来的少于原始数字。在Excel中,应该会出现一些数字,但是对于我编写的C程序函数,它们小于该数字。
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");
}
最佳答案
关于:我想知道发生数据丢失的地方。
没有数据丢失。而是,有些重复的data(key)值。
如果有重复项,则节点数不会增加。
关于c - 计算C中的文本文件数时发生数据丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58155640/