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

问题描述

我想创建一个算法,当用户被要求从键盘输入 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);
    

}

我已经写了这个,但它给了我这个错误

[Error] ld returned 1 exit status

解决方法

您已经初始化了 y、j 和 k。有一种更简单的方法来计算从 1 到 n 的总和。

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

1.变量未初始化。

2.多次重新创建变量导致没有保存值。

3.难以阅读。

试试这个:

use nampespace\MyMap;