简体   繁体   English

C ++比较器保证和内部运作

[英]C++ comparator guarantees and inner workings

Solving this problem , I found that 解决这个问题 ,我发现

if(!(p<arr[i]))

and

if(p>=arr[i])

May have different results( p is a long long and arr[i] is a double ), since the first solution is accepted and the second is not. 可能会有不同的结果( plong longarr[i]double ),因为第一个解决方案被接受,第二个解决方案不被接受。 Why? 为什么?

Complete code for context: 上下文的完整代码:

#include <bits/stdc++.h>
#define EPS (1e-5)
using namespace std;
typedef long long ll;
double arr[10005];
int main(){
    ll D,p;
    string s;
    while(getline(cin,s)){
        stringstream ss(s);
        ss>>D>>p;
        int n=0;
        while(ss>>arr[n]) ++n;
        ll dmin=D+1;
        if(n<D+1){
            double a=arr[n-4];
            double b=arr[n-3];
            double c=arr[n-2];
            double d=arr[n-1];
            double den=a*c-b*b;
            double s=(c*c-b*d)/den;
            double t=(a*d-b*c)/den;
            for(int i=n;i<=D;++i)
                arr[i]=s*arr[i-2]+t*arr[i-1];
        }
        for(int i=0;i<=D;++i){
            if(!(p<arr[i]))
                dmin=min(dmin,D-i);
            else
                break;
        }
        if(dmin==0) cout<<"The spider may fall!"<<endl;
        else if(dmin==D+1) cout<<"The spider is going to fall!"<<endl;
        else cout<<dmin<<endl;
    }
}

If !(a<b) and (a>=b) are different then the most likely explanation is that one of them is a NaN. 如果!(a<b)(a>=b)不同,则最可能的解释是其中之一是NaN。 Any comparison involving a NaN results in false , so if b is a NaN, then both (a<b) and (a>=b) will be false, and !(a<b) will be true. 任何涉及NaN的比较都会导致false ,因此,如果b是NaN,则(a<b)(a>=b)都将为false,而!(a<b)将为true。

Looking at your code, first: 首先查看您的代码:

double den=a*c-b*b;
double s=(c*c-b*d)/den;
double t=(a*d-b*c)/den;

There is no obvious reason why den cannot be zero, in which case both s and t will be infinities. 没有明显的理由为什么den不能为零,在这种情况下st都是无穷大。 Then, you compute: 然后,您计算:

for(int i=n;i<=D;++i)
  arr[i]=s*arr[i-2]+t*arr[i-1];

If s and t are inifinities, then there is ample room for the sum which produces arr[i] to be a NaN. 如果st是无穷大,则有足够的空间来产生arr[i]为NaN。 The sum of two infinities of the same sign is the infinity itself, but the sum of two infinities of opposite signs is a NaN. 具有相同符号的两个无限大的和是无穷大本身,但是具有相反符号的两个无限大的和是NaN。 Also, the product of 0 and infinity is a NaN. 同样,0和无穷大的乘积是NaN。

And once a NaN gets into arr , it will propagate, since each element depends on the previous one. 一旦NaN进入arr ,它将传播,因为每个元素都取决于前一个元素。

So you probably need to do something if den is 0. 因此,如果den为0,则可能需要执行某些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM