[TUHS] A c program problem

Dan Cross crossd at gmail.com
Thu Aug 23 00:21:45 AEST 2018


Note, TUHS probably isn't the *best* forum to ask for help with basic C
programs. :-)

That said, I suspect you mis-transcribed the program and that the line,
`sum = sum + 1;` should be `sum = sum + i;`, or more idiomatically, `sum +=
i;`.  Indeed, the whole program could be written:

#include <stdio.h>

int
main(void)
{
        int i, sum = 0;
        for (i = 1; i <= 100; i++)
                sum += i;
        printf("%d\n", sum);
        return 0;
}

If you're using a C99 or later compiler, you can be slightly more succinct:

#include <stdio.h>

int
main(void)
{
        int sum = 0;
        for (int i = 1; i <= 100; i++)
                sum += i;
        printf("%d\n", sum);
        return 0;
}

Hope that helps!

       - Dan C.


On Wed, Aug 22, 2018 at 8:17 AM cc <caipenghui_c at 163.com> wrote:

> Hello everyone
>
> I had a problem compiling a piece of c code from the book. The result of
> running the book is 5050, but the compiler is 100. I don't know which is
> right, please help me to see which is wrong. Thank you very much!
>
> #include <stdio.h>
>
> int main(void)
> {
>        int i, sum = 0;
>        i = 1;
>        while ( i <= 100) {
>        sum = sum + 1;
>        i++;
>        }
>        printf("%d\n", sum)
>        return 0;
> }
>
>
>
> cc
> 邮箱:caipenghui_c at 163.com
>
> <https://maas.mail.163.com/dashi-web-extend/html/proSignature.html?ftlId=1&name=cc&uid=caipenghui_c%40163.com&iconUrl=https%3A%2F%2Fmail-online.nosdn.127.net%2Fwzpmmc%2Fad31362036872a624ad455630205a987.jpg&items=%5B%22%E9%82%AE%E7%AE%B1%EF%BC%9Acaipenghui_c%40163.com%22%5D>
>
> 签名由 网易邮箱大师 <https://mail.163.com/dashi/dlpro.html?from=mail88> 定制
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://minnie.tuhs.org/pipermail/tuhs/attachments/20180822/527f626f/attachment.html>


More information about the TUHS mailing list