2014-01-11 73 views
0

我有這個問題,我應該這樣做。在C中使用pow()

[報告說,創建一個程序,是能夠計算和顯示的總和小號]

像S = 1 + 1/4 + 1/8 + 1月16日......直至1/[2 POW N]

所以我的工作就可以了,用這個代碼

#include <stdio.h> 
void main() 
{ 
int n,i; 
float p,s; 
printf("Enter the maximum power n :"); 
scanf("%d",&n); 
s=0; 
p=0; 
for (i=0;i<n;i++) 
{ 
    p+=1/pow(2, i); 
    s+=p; 
    printf("s = %f\n",s); 
} 
printf("The sum of this equation is :%f",&s); 
} 

想出但是,當我執行它總是像S = 0。 我在做什麼錯?

+1

您的意思是1 + 1/4 + 1/8 ...或1+ ** 1/2 ** + 1/4 + 1/8 ...? –

+0

否1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64 ... – OsomePersan

回答

1

要打印的地址(」 &小號) with%F`變量。使用錯誤的符調用未定義行爲,你可能會得到什麼。

而且,無需可變s的。刪除行

s+=p; 

應該是這樣:

#include <stdio.h> 
int main(void) 
{ 
    int n,i; 
    float p; 
    printf("Enter the maximum power n :"); 
    scanf("%d",&n); 
    p=0; 
    for (i=0;i<n;i++) 
    { 
     p+=1/pow(2, i); 
     printf("p = %f\n",p); 
    } 
    printf("The sum of this equation is :%f",p); 
} 
+1

你太棒了。謝謝。 – OsomePersan

+0

我很高興它幫助你:) – haccks

0

個只是一個猜測,你可能會取代線

p+=1/pow(2, i); 

p+=1.0f/(float)pow(2, i); 

printf("The sum of this equation is :%f",&s); 

printf("The sum of this equation is :%f",s); 
+2

第一次改變是不必要的。 –

+0

如果他使用標準的編譯器,是的。 – user287107

+0

好奇,非標準編譯器不喜歡'p + = 1/pow(2,i)的問題是什麼;'?將((double)'縮小到'(float)'? – chux

1

您需要包括<math.h>得到適當的原型pow()

您可能需要鏈接到數學庫太gcc main.c -Wall -lm

0

錯字可能是..但你將有發言權%fs(不&s

printf("The sum of this equation is :%f",s); 

在邊注:

一旦包含<math.h>,您將得到使用正確的pow(..)原型的編譯器警告。下面的代碼將是相關的。

p+=1.0f/(float)pow(2.0f, i); 
1
#include <math.h> 
.... 
for (i=0;i<n;i++) 
{ 
    p=1/pow(2, i); 
    s+=p; 
    printf("s = %f\n",s); 
} 
printf("The sum of this equation is :%f",s); 
+0

謝謝你,先生。現在工作正常。 – OsomePersan

1

你的程序有多個問題。啓用編譯器警告應該告訴你其中的一些。

  1. 您應該包含C標頭,其中包含pow函數的聲明。
  2. 您添加兩個加數。
  3. 在您的第二條printf聲明中,您通過了float。但%f格式說明符需要double參數。在你的第三條printf語句中,你傳遞一個指向float的指針。

另一個美容問題是您的main函數應返回int