gpt4 book ai didi

c++ - 代码在不同的编译器上产生不同的输出

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:01 25 4
gpt4 key购买 nike

我正在解决 Quasi-Binary Codeforces 上的问题(无关紧要),这是我的 submission .这是我生成的代码:

#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;
};

关于c++ - 代码在不同的编译器上产生不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com