gpt4 book ai didi

c - 整数与 float : Counter

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:38 29 4
gpt4 key购买 nike

代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <time.h>

int main()
{
FILE *fp1, *fp2;
int ch1, ch2;
clock_t elapsed;
char fname1[40], fname2[40];

printf("Enter name of first file:");
fgets(fname1, 40, stdin);
while ( fname1[strlen(fname1) - 1] == '\n')
{
fname1[strlen(fname1) -1] = '\0';
}

printf("Enter name of second file:");
fgets(fname2, 40, stdin);
while ( fname2[strlen(fname2) - 1] == '\n')
{
fname2[strlen(fname2) -1] = '\0';
}

fp1 = fopen(fname1, "r");
if ( fp1 == NULL )
{
printf("Cannot open %s for reading\n", fname1 );
exit(1);
}

fp2 = fopen( fname2, "r");
if (fp2 == NULL)
{
printf("Cannot open %s for reading\n", fname2);
exit(1);
}

elapsed = clock(); // get starting time

ch1 = getc(fp1); // read a value from each file
ch2 = getc(fp2);

float counter = 0.0;
float total = 0.0;

while(1) // keep reading while values are equal or not equal; only end if it reaches the end of one of the files
{
ch1 = getc(fp1);
ch2 = getc(fp2);

//printf("%d, %d\n", ch1, ch2);// for debugging purposes

if((ch1 ^ ch2) == 0)
{
counter++;
}

total++;

if ( ( ch1 == EOF) || ( ch2 == EOF)) // if either file reaches the end, then its over!
{
break; // if either value is EOF
}
}

fclose (fp1); // close files
fclose (fp2);

float percent = (counter / (total)) * 100.0;

printf("Counter: %.2f Total: %.2f\n", counter, (total));
printf("Percentage: %.2f%\n", percent);

elapsed = clock() - elapsed; // elapsed time
printf("That took %.4f seconds.\n", (float)elapsed/CLOCKS_PER_SEC);
return 0;
}

尝试比较两个大约 1.4 GB 的 .nc 文件,这些是我的结果:

$ gcc check2.c -w
$ ./a.out
Enter name of first file:air.197901.nc
Enter name of second file:air.197902.nc
Counter: 16777216.00 Total: 16777216.00
Percentage: 100.00%
That took 15.6500 seconds.

它们不可能 100% 相同,哈哈,关于为什么它似乎停在第 16777216 个字节有什么想法吗?

计数器应该是 1,256,756,880 字节

1.3 GB(1,256,756,880 字节)

我在这里下载了这个气候数据集:

ftp://ftp.cdc.noaa.gov/Datasets/NARR/pressure/

提前感谢您的帮助

最佳答案

float 数据类型仅精确到 6 位有效数字,不适用于 countertotal。任何浮点类型在任何情况下都是不合适的。这有很多问题,尤其是 ++ 是一个整数运算符,从 float 到 int 的隐式转换,递增,然后返回到 float 将大于 6 位的整数值失败。

我假设您选择这种类型是因为它的范围可能比unsigned int大?我建议您对这些变量使用 unsigned long long

unsigned long long counter = 0;
unsigned long long total = 0;

...

float percent = (float)counter / (float)total * 100.0f ;

关于c - 整数与 float : Counter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844977/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com