比较两个不同的双精度数时返回true

Return true while comparing two different double numbers

本文关键字:双精度 true 返回 两个 比较      更新时间:2023-10-16

输出中有双位数

344.6
563.4
455.6
10.7
10.6
1

最后两个显示

    [0] 10.000000000000000  double
    [1] 10.000000000000000  double
visual studio express 2015中的locals变量

repRate[0]==repRate[1]
true

为什么?我试着用(双份)来确认。输出给我两个不同的数字,但是repRate[0]==repRate[1]返回true。

this is the input.
    5
    1 10 3456
    2 10 5644
    3 10 4566
    4 20 234
    5 20 232

5表示您有5个项目,1为id代码,10为初始数字,3456为最终数字。复制率是(3456-10)/10,我需要使用复制率作为索引对数组进行排序。

#include <iostream>
using namespace std;
int main() {
int n;
int a[110][4];
double repRate[110];
//input
cin >> n;
for (int i = 0; i < n;i++) {
    cin >> a[i][0] >> a[i][1] >> a[i][2];
}
//rep rate
for(int i = 0;i < n;i++){
    repRate[i] = (double) ((double)a[i][2]- (double)a[i][1]) / (double)a[i][1];
    cout << repRate[i] << endl;
}
//sort
for (int i = 0;i < n;i++) {
    for (int j = 0;j < n - i-1;j++) {
        int temp[5];
        int rtemp;
        if (repRate[j]>repRate[j+1]) {
            rtemp = repRate[j+1];
            repRate[j + 1] = repRate[j];
            repRate[j] = rtemp;
            for (int k = 0;k < 4;k++) {
                temp[k] = a[j+1][k];
            }
            for (int k = 0;k < 4;k++) {
                a[j+1][k] = a[j][k];
            }
            for (int k = 0;k < 4;k++) {
                a[j][k] = temp[k];
            }
        }
    }
}
int test;
test = repRate[0] == repRate[1];
cout << test;

return 0;
}

尝试将rtemp设置为double,因为这一行:

rtemp = repRate[j+1];

会减少一些准确性。如果没有启用警告,这应该是对编译器的警告!

之后输出如下所示:

5
1 10 3456
2 10 5644
3 10 4566
4 20 234
5 20 232
344.6
563.4
455.6
10.7
10.6
0