小编Đum*_*lav的帖子

为什么函数不给出整数溢出

我用C++和Pascal编写了函数,给出了第n个Fibbonacci数.正如预期的大n值(n> 92,因为甚至f(93)> 2 ^ 63 + 1)我得到了不正确的结果.
但是当我将它们与相同的n进行比较时,我会在两种语言中得到相同的结果.

这与我的想法相反,我会得到一些随机数.
我想知道为什么我得到相同的结果以及为什么我首先没有得到整数溢出.

有人可以向我解释一下吗?

码:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

long long fibo(int n){
    long long a1,a2,pom;
    int i=1;
    a1 = 0; a2 = 1;
    while(i<=n){
        pom = a2;
        a2 = a1 + a2;
        a1 =  pom;
        i++;
    }
    return a1;
}

int main(){
    int n;
    cin >> n;
    cout << "Function: "<< setprecision(50) << fibo(n) << endl;
}
Run Code Online (Sandbox Code Playgroud)
Program AddNums(output);
function fibo(n:integer):int64;
    var
        a1,a2,pom:int64;
        i:integer;
    begin
        a1:=0;a2:=1;i:=1;
        while(i<=n)do …
Run Code Online (Sandbox Code Playgroud)

c++ pascal function fibonacci

1
推荐指数
1
解决办法
120
查看次数

C 编译器行为不匹配

我编写了以下代码以测试它是否可以通过指针a修改常量c。我已经在 Clang、VC 和 GCC 编译器中对其进行了测试,并观察到 ​​VC 和 GCC 代码都按我的预期工作,它将 6 打印到标准输出,而当我用 Clang 编译它时,该值没有被修改,而 5打印到标准输出。

#include <stdio.h>

int main(void) {
  const int c = 5;
  int* a  = (int*) &c;
  *a = 6;
  printf("%d", c);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想知道对此是否有任何众所周知的解释,或者它与编译器的内部结构和其他难以分析的东西有关。提前谢谢大家!

c pointers constants

1
推荐指数
1
解决办法
47
查看次数

标签 统计

c ×1

c++ ×1

constants ×1

fibonacci ×1

function ×1

pascal ×1

pointers ×1