![](/img/trans.png)
[英]C program to find the sum of all odd integers up to n using while-loop
[英]How do I make the loop go n times to find sum of nth terms? In C program
問題是:編寫一個 C 程序,使用循環 {1+2+4+8....} 確定以下系列的前 N 項之和
我試過的代碼是:
#include <stdio.h>
int main(void){
int i,sum=0,n;
scanf("%d",&n);
for(i=1;i<n;i*=2)
{
sum=sum+i;
}
printf("Sum=%d\n",sum);
return 0;
}
問題是,當我輸入 N 作為 5 時,它給出的 output 為 7,但我期望的 output 是 31。
如,5項之和=1+2+4+8+16=31
所以,我想知道如何讓我的循環重復 5 次或第 n 次,以獲得預期的結果。
您的問題是i
不是每次迭代增加 1 而是乘以 2。您需要添加另一個變量來計算迭代次數。
#include <stdio.h>
int main(void){
int i,value=1,sum=0,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
sum=sum+value;
value *= 2;
}
printf("Sum=%d\n",sum);
return 0;
}
另外,因為 1+2+4+...+2^(n - 1) == 2^n - 1 (^ 代表冪),所以可以不用循環,用位移位來計算。
#include <stdio.h>
int main(void){
int sum,n;
scanf("%d",&n);
sum = (1 << n) - 1; // 1 << n equals to 2^n
printf("Sum=%d\n",sum);
return 0;
}
不要更新您的變量,該變量已被賦予跟蹤術語數量的任務。
由於這個問題與幾何級數有關,因此您也可以使用它的屬性來計算總和
級數公式之和:a(r n -1)/(r-1),其中a:First Term,r:公比
此外,為scanf
添加錯誤檢查。
這是它的代碼片段:
#include <stdio.h>
int main(void) {
int i, sum=0,n,value=1;
if(scanf("%d", &n)!=1){
fprintf(stderr,"Please input the valid number");
return -1;
}
for (i=0;i<n;i++)
{
sum +=value;
value *=2;
}
printf("Sum=%d\n", sum);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.