为什么两个不同的编译器会给出两种不同的结果



问题是找到数字(1358(^n的最后一位。我在c++中使用了相同的方法,使用了两个不同的编译器,但这两个编译器在代码集上的结果不同。

编译器:clang c++17 Diagnostics(接受代码(,但GNU G++17的判决是错误的

我不知道问题出在哪里,为什么两个编译器的结果不同?

n=[01000000000]

测试用例:1000000000、32、33、36

正确答案:6,6,8,6

但是使用GNU编译器:1,1,8,6

#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
double n; cin >> n;
vector<long long> res{ 1, 8, 4, 2, 6 };
if (n <= 4){
cout << res[n] << "n";
}
else{
while (n > 4){
double x = log10(n)/log10(2);
n = (ceil(x) == floor(x))? 4 : n - pow(2, floor(x));
}
cout << res[n] << "n";
}
return 0;
}

我无法重现您的问题,但这可能是由于浮点舍入错误造成的(请参阅浮点数学坏了吗?(。

没有必要使用浮点来解决这个问题。你似乎已经意识到,最后一个数字遵循8、4、2、6的重复模式。要找到您正在使用的这个模式的哪个元素,您可以简单地使用n % 4:

#include <iostream>
#include <vector>
#include <cmath>
int main() {
for (int n : {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 32, 33, 36, 1000000000})
{
std::vector<int> res{ 1, 8, 4, 2, 6 };
n = (n - 1) % 4 + 1;
std::cout << res[n] << "n";
}
return 0;
}

最新更新