简体   繁体   English

使用 C 中的循环对前 n 个数字(从 1 到 n)求和

[英]Sum the first n numbers (from 1 to n) using loops in C

I want to create an algorithm that allows you to sum the first n numbers (from 1 to n) once the user is asked to enter n from the keyboard.我想创建一个算法,一旦要求用户从键盘输入 n,您就可以对前 n 个数字(从 1 到 n)求和。

#include <stdio.h>

int main() {
    
    int x,k,j;
    
scanf("%d",&x);
    
    int y= 1;
    
do {
    
    int k= y;
    
    int y= y+1;
    
    int j= k+y;
    
}   while(y<x);


printf("The Total sum of the number is: %d ", j);
    

}

I have wrote this but it gives me this error:我写了这个,但它给了我这个错误:

[Error] ld returned 1 exit status

You already initialized y, j and k.您已经初始化了 y、j 和 k。 There is a simplier way to count sum from 1 to n.有一种更简单的方法可以计算从 1 到 n 的总和。

scanf("%d", &n);
int sum=0;
for(int i=1; i<=n; i++){
    sum=sum+i;
}

1.Variables are not initialized. 1.变量未初始化。

2.Re-create variables too many times resulting in no saved values. 2.重新创建变量太多次导致没有保存值。

3.Hard to read. 3.难读。

Try this:尝试这个:

#include <stdio.h>

int main() {
    int end = 0, sum = 0;
    scanf("%d",&end);
    int i = 1;
    do {
        sum = sum + i;
        i= i+1;
    } while(i<=end);

  printf("The Total sum of the number is: %d ", sum);
}

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

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