Why is one of the cases incorrect?

Asked

Viewed 52 times

0

Good evening, I wonder, why my code return a wrong value for a case in which the input is 1.1 and 100000, the output should give 100000 and 5000050000 and this giving 100000 and 705082704?? the output should be double or float??

#include <stdio.h> //Bibliteca para as fuñcoes de entrada e saida

int main (void) //Programa principal

{
    int a1, r, n, An, Sn; //Declaracao das variaveis necessarias 
    scanf("%d\n%d\n%d",&a1, &r, &n); //Insercao dos valores de A1, r e n

    An = a1+(n-1)*r; //Formula para encontrar o enesimo termo da PA
    printf("%d\n", An); //Impressao na tela do valor do enesimo termo encontrado

    Sn = (a1+An)*n/2; //Formula para fazer a soma dos "n" termos da PA
    printf("%d", Sn); //Impressao na tela do valor da soma da PA

return 0;

}

2 answers

1

Because you crossed the line to int of your computer.

5000050000 is more than 2 31-1 (2147483647).
Your show suffers from Helpless Behavior.


5000050000(10) == 100101010000001101011010101010000(2) // 33 bits
                   00101010000001101011010101010000(2) = 705082704(10)
  • And how can I solve this problem??

  • You can use a data type with upper limits (long for example), or if you intend to use really large numbers (with thousands of bits) use a bignum library (article in English).

0

In fact the limit really exceeds that of the usual integers. Just exchange them for longs

#include <stdio.h>

int main(void)
{
    long a1, r, n, An, Sn; 
    scanf("%ld %ld %ld",&a1, &r, &n); 

    An = a1 + (n - 1) * r; 
    printf("%ld\n", An); 

    Sn = (a1 + An) * n/2; 
    printf("%ld\n", Sn); 

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.