编程1到100怎么编

时间:2025-01-26 07:55:41 网络游戏

C语言

使用for循环

```c

include

int main() {

int sum = 0;

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

sum += i;

}

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

return 0;

}

```

使用while循环

```c

include

int main() {

int sum = 0;

int i = 1;

while(i <= 100) {

sum += i;

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 += i;

i++;

} while(i <= 100);

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

return 0;

}

```

使用递归

```c

include

int function(int num) {

if(num < 100) {

return num + function(num + 1);

}

return num;

}

int main() {

int sum = function(1);

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

return 0;

}

```

汇编语言

方法一

```assembly

MOV CX,100

MOV AX,0

MOV BX,1

AGAIN: ADD AX,BX

INC BX

LOOP AGAIN

```

方法二

```assembly

MOV CX,100

MOV AX,0

LOOP1: ADD AX,CX

LOOP LOOP1

```

其他语言

Python

```python

sum = sum(range(1, 101))

print(sum)

```

Java

```java

public class Main {

public static void main(String[] args) {

int sum = 0;

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

sum += i;

}

System.out.println("Sum of numbers from 1 to 100: " + sum);

}

}

```

JavaScript

```javascript

let sum = 0;

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

sum += i;

}

console.log("Sum of numbers from 1 to 100: " + sum);

```

这些示例展示了如何使用不同的编程语言和技术来计算1到100的和。你可以根据自己的需求和熟悉程度选择合适的方法。