Why is one of the cases incorrect?

0

Good night, I wonder, why my code returns a wrong value for a case where the input is 1.1 and 100000, the output should give 100000 and 5000050000 and this is 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;

}
    
asked by anonymous 18.04.2015 / 22:46

2 answers

1

Because you have exceeded the limits for int of your computer.

5000050000 is more than 2 ^ 31-1 ( 2147483647 ). Your program suffers from Comfortably Undefined.

5000050000(10) == 100101010000001101011010101010000(2) // 33 bits
                   00101010000001101011010101010000(2) = 705082704(10)
    
18.04.2015 / 22:54
0

In fact, the limit actually exceeds that of the usual integers. Just change them by long s

#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;
}
    
18.04.2015 / 22:53