[英]Code producing different output on different compilers
我正在解决Codeforce上的准二进制问题(无关紧要),这是我的建议 。 这是我产生的代码:
#include <iostream>
#include <cmath>
using namespace std;
int quasi_binary(int num, int tens)
{
int res,digit;
if(num == 0)
{
return 0;
}
digit = num%10;
num = num/10;
res = quasi_binary(num, tens+1);
if(digit)
{
cout << 1;
return ((digit-1)*pow(10,tens)+res);
}
else
{
cout << 0;
return res;
}
}
int main()
{
int n,k=-1,temp,digit;
cin >> n;
//this loop calculates the value of k,as it needs to be printed first
temp=n;
while(temp)
{
digit = temp%10;
temp = temp/10;
if(digit>k)
k=digit;
}
cout << k << endl;
//print those k quasi-numbers
while(n)
{
n = quasi_binary(n,0);
cout << " ";
}
return 0;
}
我看不到任何可以在不同编译器上产生未定义行为的语句。 为了避免歧义,我在适当的地方使用了适当的括号。 仍然会出现不确定的行为。 任何人都可以帮助找到产生未定义行为的语句/指令。
输入
415
输出(在线判断)-不正确
5
111 101 101 11 11 11 11 11 11 11 11 11
输出(在装有gcc的64位PC上)-正确
5
111 101 101 101 1
为避免舍入到小于数学结果的1,将pow(10, tens)
替换为int( 0.5 + pow( 10, tens ) )
。
或者,编写您自己的整数幂函数。
例如
using Int_noneg = int; // "Not negative"
auto int_pow( Int_noneg const x, Int_noneg const exponent )
-> int
{
Int_noneg reverse_bits = 0;
Int_noneg n_exponent_bits = 0;
for( Int_noneg i = exponent; i != 0; i /= 2 )
{
reverse_bits = 2*reverse_bits + i%2;
++n_exponent_bits;
}
Int_noneg result = 1;
for( Int_noneg i = 0; i < n_exponent_bits; ++i, reverse_bits /= 2 )
{
result *= result;
if( reverse_bits % 2 != 0 ) { result *= x; }
}
return result;
};
在进入我的解决方案之前,我带了一个团队,去了您在帖子中引用的站点(不需要这样做)。 我提交了您发布的原始代码,是的,您得到了错误。 因此,在我在主注释部分链接的SO注释中, pow
函数确实由于浮点和截断问题而导致了问题。
为了解决这个问题,您可以做一些事情,大部分都在给出的其他答案中进行了概述。 但我会给出解决方案:
unsigned long powTable[] = { 1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000 };
//...
return ((digit-1)*powTable[tens]+res);
而不是调用pow
函数,而是声明一个具有10的幂的简单查找表,然后将tens
用作该表的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.