E
E
Egorithm2016-07-02 11:47:01
C++ / C#
Egorithm, 2016-07-02 11:47:01

How to get rid of overflow?

I wrote this program to display the Fibonacci series (0,1,1,2,3,5,8,13,21,34,55,89...):

#include <stdio.h>

void main(void) {
  double a, b;
  int n;

  a = 0;
  b = 1;

  system("TITLE fibonachi");
  system("COLOR F1");
  printf("Введите количество итераций (не меннее двух):\t");
  scanf("%d", &n); 
  printf("\n%.0f\n%.0f\n", a, b);

  n -= 2;
  while(n > 0) {
    a += b;
    printf("%.0f\n", a);
    n--;
    if(n > 0) {
       b += a;
       printf("%.0f\n", b);
       n--;
    }
  }

  system("PAUSE");
}

Here's what happened:
3345c4fbb3d841819f6a784a6e407a6e.png
If we replace it with unsigned int and output as %u , then here's what happens:
4fffc73455824674916fe67519740006.png
Although I read somewhere that there shouldn't be an overflow of unsigned integers.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2016-07-02
@EgoRusMarch

I read somewhere that there shouldn't be overflows of unsigned integers.

There is no magic in unsigned integers, the maximum representable number is 2^(number of bits)-1, large numbers remain modulo 2^(number of bits). This behavior is described by the C language standards.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question