【发布时间】:2018-07-11 22:14:04
【问题描述】:
我没有除以零,并且我的代码中没有浮点数据类型,我仍然得到浮点异常。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
unsigned long long int t,n;
cin>>t;
while(t--)
{
cin>>n;
unsigned long long int deno = pow(10,n-1),count=2,sum = 0,f1=1,f2=1;
while(1){
sum = f1+f2;
f1 = f2;
f2 = sum;
count++;
if((int)(sum/deno)>0){
cout<<count<<endl;
break;
}
}
}
return 0;
}
之前的所有问题都有类似的除以零的问题,但变量 deno 永远不能像n>=2那样为零。
我之前的研究:
- “Floating point exception” in code that contains no floats
- Floating Point Exception C++ Why and what is it?
问题说明:https://www.hackerrank.com/contests/projecteuler/challenges/euler025/problem
它通过了 2 个测试用例,失败了 2 个。都是隐藏的测试用例。 Result image
通过输入 1 50 我们可以重现错误。详情:
GDB trace: Reading symbols from solution...done. [New LWP 15127] Core
was generated by `solution'. Program terminated with signal SIGFPE,
Arithmetic exception.
#0 main () at solution.cc:23
23 if((int)(sum/deno)>0){
#0 main () at solution.cc:23
【问题讨论】:
-
浮点执行是当您尝试除以 0 或取模时。它不是浮点独有的
-
重现问题需要多长时间?当我运行您的代码时,它会一直运行。
-
使用你的调试器。观察
deno的值,看看它是否为零。 -
如果您不知道导致问题的输入,@Yılmazedis 调试不会轻易提供帮助。
-
您是否意识到
unsigned long long只能上升大约 19 位,而问题需要 5000?即使是long double也只能达到 308 位(当然会出现浮点错误)。您将需要一种新方法。
标签: c++ c++14 floating-point-exceptions