Fibonacci sequence works in python, but not in c?

I have the following python code:

a, b = 1, 1 for i in range(0, 100): print a a, b = b, a + b 

It generates this: 1 1 2 3 5 8, etc.

I wrote the same thing in c:

 #include <stdio.h> long long unsigned int a = 1, b = 1; void main(){ for(int i = 0; i < 100; i++){ printf("%llu \n", a); a = b, b = a + b; } } 

It generates this: 1 1 2 4 8 16 32 etc.

Why does program c generate permissions 2 when it uses the same operations?

+5
source share
3 answers
 a, b = b, a + b 

in python packs the values โ€‹โ€‹of b and a + b into a tuple, then unpacks it back to a and b .

C does not support this function, but uses a comma to separate between assignments, so a = b, b = a + b translates as

 a = b; b = a + b; 

where b gets a doubling every time because the assignment is not simultaneous.

To fix this, you will have to assign each variable separately:

 b = a + b; a = b - a; // a + b - a = b 
+10
source

Because it has different meanings in C and python. In python:

 a, b = b, a + b 

means the change in a and b (simultaneously) with the corresponding values โ€‹โ€‹of b and a+b .

So far in C:

  a = b, b = a + b; 

means do a=b , and then after b=a+b .

+3
source

You misunderstand the comma operator .

 #include <stdio.h> #include <inttypes.h> #include <stdint.h> int main(void) { uintmax_t a = 1, b = 1; for (int i = 0; i < 100; i++) { printf("%" PRIuMAX "\n", a); b = a + b; a = b - a; } } 
0
source

Source: https://habr.com/ru/post/1268597/


All Articles