c - C程序发生数据丢失
问题描述
我尝试制作一个函数来从文本文件中获取数字并计算不重叠并超过某个数字的数字。我要把它放在链表中。计算一个与创建链表不重叠的数字是一件好事,但是计算超过某个数字的数字就有问题了。它比原来的数字少。在 Excel 中,应该有一些数字,但在我制作的 C 程序函数的情况下,它们小于那个数字。
#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");
}
上面的代码是我的程序代码。我正在使用一种方法从input.txt文件中获取一个数字,将其放入newData变量中,如果超过5000,则增加Data_morethan5000_Count的值。所以结果应该是45460。但是,C程序输出了一个结果值 45432。我想知道数据丢失发生在哪里。
解决方案
推荐阅读
- flutter - 试图将数据发送到第二页
- c# - 我没有使用 request.QueryString 从 sql 数据中获取值
- php - Laravel 中使用队列的问题
- c# - 如何检测用户何时在 WPF C# 中添加或删除程序
- spring - Spring:使用@Transactional(propagation=Propagation.SUPPORTS) 的方法与没有@Transactional 的方法之间的区别
- python - 下面的例子被认为是有效的吗?如果没有,那怎么能更好呢?
- php - 使用 php 登录 Google 的问题
- swift - UICollectionView 数据源和委托导致应用程序终止
- java - IntelliJ 社区版中的 Spring Boot 项目
- javascript - 鼠标进入时,角度引导弹出框消失