简体   繁体   English

C编程加自然数

[英]C programming adding natural numbers

I need my program to run and tell me the sum of the natural number entered also it needs to say along with the sum total i need it to show the sum of odd and even integers. 我需要我的程序运行,并告诉我输入的自然数的总和,还需要说它与总和,我需要它来显示奇数和偶数整数的和。 This is what I have so far and it won't run correctly in C. 这是我到目前为止的内容,它将无法在C中正确运行。

#include <stdio.h>
int main (void)
{
    int n, i, sum = 0;
    int sum1 = 0;
    int sum2 = 0;
    printf("enter a number and I will tell you the numbers sums.");
    scanf("%d", &n);

    for(i=1; i<= n; ++n)
    {
        sum2 = sum2 + n;
    }
    for(i=2; i<= n; ++n)
    {
        sum1 = sum1 + n;
    }
    for(i=1; i<= n; ++n)
    {
        sum += i;
    }
    printf("sum of integers is %d" ,sum);
    printf("sum of odd integers is %d" ,sum1);
    printf("sum of even integers is %d" ,sum2);

    return 0;
}

In your loops to count odd and even, you need to increment by 2 in the loop, not one. 在循环中计算奇数和偶数时,您需要在循环中增加2,而不是1。 Instead of ++i , use i += 2 : 代替++i ,使用i += 2

for (i = 2; i <= n; i += 2)

And it should be i in the increment, not n . 它应该是i而不是n You're changing the value of your final variable. 您正在更改最终变量的值。 Further, unless I'm misunderstanding what you're trying to do, you should be adding i to your sums, not n . 此外,除非我误解了您要做什么,否则您应该将i加到您的总和上,而不是n

The sum of the first N natural numbers is a well-known formula, 前N个自然数之和是众所周知的公式,

sum(range(1,N)) == N*(N+1)/2

Read this exposition, and then see if you can derive a formula for the sum of even or odd, http://mathandmultimedia.com/2010/09/15/sum-first-n-positive-integers/ 阅读此博览会,然后查看是否可以导出偶数或奇数和的公式, http://mathandmultimedia.com/2010/09/15/sum-first-n-positive-integers/

(hint: the sum of every other number would be about 1/2) (提示:其他所有数字之和约为1/2)

You only require a one for loop here's how 您只需要一个for循环,这就是方法

sum = sum1= sum2 =0;
for(i=0; i<= n; i++)
{
sum = sum +i;
if(i %2 == 0)
sum2 += i;
else
sum1 +=i;
}

use if statement for filtering numbers and don't forget to initialise all sum var to 0 使用if语句过滤数字,不要忘记将所有sum var初始化为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM