输入正整数n,求s=(1+2)+(2+3+4)+(3+4+5+6)+…多项式的值C语言
时间: 2023-12-21 14:29:48 浏览: 16
以下是C语言求多项式的代码:
```c
#include <stdio.h>
int main()
{
int n, i, j, s = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
int b = 0;
for (j = 1; j <= i; j++) {
b += j;
}
s += b;
}
printf("%d", s);
return 0;
}
```
相关问题
计算s=1+2+3+4.。。。+其中n由键盘输入
抱歉,我是一个语言模型,无法接收键盘输入。不过,我可以提供一个Python程序来计算s=1+2+3+4+...+n,你可以在本地运行它并输入n的值:
```
n = int(input("请输入n:"))
s = 0
for i in range(1, n+1):
s += i
print("s的值为:", s)
```
运行程序后,它会提示你输入n的值,你可以输入任意正整数,然后程序会计算出s的值并输出。例如,如果你输入10,程序会输出s的值为55,因为1+2+3+4+5+6+7+8+9+10=55。
用java从键盘上输入正整数n,利用递归方法求s=1+3+5+7+…+ (2n+1)
以下是Java代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入正整数n:");
int n = sc.nextInt();
System.out.println("结果为:" + getSum(n));
}
public static int getSum(int n) {
if (n == 1) {
return 1;
} else {
return getSum(n - 1) + 2 * n - 1;
}
}
}
```
首先从键盘读取正整数n,然后调用getSum方法计算结果。getSum方法采用递归实现,当n等于1时,返回1;否则返回getSum(n - 1) + 2 * n - 1,即前n-1个奇数之和再加上第n个奇数。最终结果即为前n个奇数之和。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)