c语言1加到100怎么编程

时间:2025-01-27 10:06:56 网络游戏

使用while循环

```c

include

int main() {

int sum = 0;

int i = 1;

while (i <= 100) {

sum = sum + i;

i = i + 1;

}

printf("Sum of numbers from 1 to 100: %d\n", sum);

return 0;

}

```

使用for循环

```c

include

int main() {

int sum = 0;

for (int i = 1; i <= 100; i++) {

sum = sum + i;

}

printf("Sum of numbers from 1 to 100: %d\n", sum);

return 0;

}

```

使用do while循环

```c

include

int main() {

int sum = 0;

int i = 1;

do {

sum = sum + i;

i = i + 1;

} while (i <= 100);

printf("Sum of numbers from 1 to 100: %d\n", sum);

return 0;

}

```

使用递归函数

```c

include

int sum_recursive(int n) {

if (n == 1) {

return 1;

} else {

return n + sum_recursive(n - 1);

}

}

int main() {

int result = sum_recursive(100);

printf("Sum of numbers from 1 to 100: %d\n", result);

return 0;

}

```

这些方法都可以实现从1加到100的求和,你可以根据自己的喜好和需求选择合适的方法。