Sum of positive values in an array gives negative result in a c program

后端 未结 4 1564
渐次进展
渐次进展 2021-01-26 10:16

I have a problem that is, when I sum the values of an array (that are all positive, I verified by printing the values of the array), I end up with a negative value. My code for

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-26 10:26

    I think your final output is going out of range. For this you will have to declare summcp as long long int

    long long int summcp = 0;
    for (k = 0; k < SIMUL; k++)
    {
        summcp += mcp[k];
    }
    printf("summcp: %lld.\n", summcp);
    

    int variable throws garbage value if its range is exceeded.

提交回复
热议问题