c语言一到十的编程怎么写

时间:2025-01-28 23:47:01 网络游戏

使用for循环打印1到10

```c

include

int main() {

int i;

for (i = 1; i <= 10; i++) {

printf("%d ", i);

}

printf("\n");

return 0;

}

```

使用while循环打印1到10

```c

include

int main() {

int i = 1;

while (i <= 10) {

printf("%d ", i);

i++;

}

printf("\n");

return 0;

}

```

使用递归计算1到10的阶乘

```c

include

long long factorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * factorial(n - 1);

}

}

int main() {

int i;

for (i = 1; i <= 10; i++) {

printf("Factorial of %d = %lld\n", i, factorial(i));

}

return 0;

}

```

使用数组和循环计算1到10的阶乘

```c

include

int main() {

int i;

long long factorial;

factorial = 1;

for (i = 1; i < 10; i++) {

factorial[i] = i * factorial[i - 1];

}

for (i = 0; i < 10; i++) {

printf("Factorial of %d = %lld\n", i, factorial[i]);

}

return 0;

}

```

使用字符串和循环打印1到10

```c

include

int main() {

char str;

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

sprintf(str, "%d", i);

printf("%s ", str);

}

printf("\n");

return 0;

}

```

这些示例展示了如何在C语言中实现从1到10的编程任务,包括打印数字、计算阶乘等。你可以根据自己的需求选择合适的方法。