Int vs Float:反击

时间:2014-07-19 21:08:28

标签: c comparison byte bit-manipulation duplication

代码:

#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/

感谢您的提前帮助

2 个答案:

答案 0 :(得分:4)

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 ;

答案 1 :(得分:0)

intcounter变量

使用total类型