我写了一个c程序,可以读取一个只有一列数据的文本文件。所有数据都可以通过以下代码读入程序:
#include <stdio.h>
#include <cstdlib>
main()
{
char temp[20];
float t;
int a = 0, x = 0; //a is no. of data greater than 180 and x is no of data
FILE *fpt;
fpt = fopen("case i.txt", "r");
fscanf(fpt, "%s", temp); // read and display the column header
printf("%s\n", temp);
while (fscanf(fpt, "%f", &t) == 1)
{
printf("%.2f\n", t);
++x; //count for number of data
if (t > 180) {
++a; //count for number of data > 180
}
if (x > 2 && a == 2) { //place where bug is expected to occur
printf("2 out of 3 in a row is greater than 180");
a=0; //reset a back to zero
x=0;
}
}
fclose(fpt);
system("pause");
}
当我想检测三分之二的数据超过180摄氏度时,问题就来了。我尝试了一些想法,比如什么时候(数据数量>2)和(两个数据>180),然后生成一个错误消息,但是它会有错误,因为它可能有两个数据>180,但是当4个数据被读取时,这意味着它变成了4个数据中的2个,而不是3个数据中的2个,有可能被编程吗?提前感谢你的帮助。
以下是示例数据和输出:
最佳答案
您需要保留一个“滑动窗口”,其中包含3个值,指示超过180的值有多少。
一种方法是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char temp[20];
float t;
const int min_over = 2;
const int max_window = 3;
const int max_value = 180;
char over[max_window]; // a 1 means over, 0 otherwise
int oi = 0;
int num_values = 0;
FILE *fpt;
fpt = fopen("case i.txt", "r");
fscanf(fpt, "%s", temp); // read and display the column header
printf("%s\n", temp);
memset(over, 0, max_window);
while (fscanf(fpt, "%f", &t) == 1)
{
int num_hit, i;
printf("%.2f\n", t);
// Calculate num_hit: how many over in a window of max_window
//
over[oi] = (t > max_value) ? 1 : 0;
if (++oi >= max_window)
oi = 0;
for ( num_hit = i = 0; i < max_window; i++ ) num_hit += over[i];
// Only check for min_over/max_window after at least
// max_window values read; Reset the check
//
if ((++num_values >= max_window) && (num_hit >= min_over))
{
printf("It happened!\n");
memset(over, 0, max_window);
num_values = 0;
}
}
fclose(fpt);
system("pause");
}
因为您需要2/3的比率,这对应于
min_over / max_window
值。我在你的评论数据示例中运行了这个:
Temperature
190.00
190.00
170.00
It happened!
200.00
190.00
100.00
It happened!
100.00
190.00
190.00
It happened!
关于c - 如何检测超出固定范围的特定值的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23114919/