2016-08-16 7 views
0

私はx - (x^3/3!)+(x^5/5!) - (x^7/7!)+ ... !)をxとnをユーザー入力として取ることによって得られます。このシリーズを印刷する方法C/C++のx-(x^3/3!)+(x^5/5!) - (x^7/7!)+ ...(x^n/n! ?

これは私が試したものです、と私はXに値を入力したときも何も出力がない、N:私は、xとnの値を入力すると

#include<stdio.h> 
#include<math.h> 
//#include<process.h> 
#include<stdlib.h> 

double series(int,int); 
double factorial(int); 

int main() 
{ 
    double x,n,res; 
    printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n"); 
    printf("\nPlease enter a value for x and an odd value for n\n"); 
    scanf("%lf%lf",&x,&n); 
    /*if(n%2!=0) 
    { 
     printf("Please enter a positive value!\n"); 
     exit(0); 
    }*/ 
    res=series(x,n); 
    printf("For the values you've entered, the value of the series is:\n %lf",res); 
} 

double series(int s, int t) 
{ 
    int i,sign=1; double r,fact,exec; 
    for(i=1;i<=t;i+2) 
    { 
     exec=sign*(pow(s,i)/factorial(i)); 
     r+=exec; 
     sign*=-1; 
    } 
    return r; 
} 

double factorial(int p) 
{ 
    double f=1.0; 
    while(p>0) 
    { 
     f*=p; 
     p--; 
    } 
    return f; 
} 

が、それは単に何も表示されません。 私はC言語で書いていますが、C++のソリューションも高く評価されています。機能series()

Output window in code::blocks

+3

ようこそスタックオーバーフロー!デバッガを使用してコードをステップ実行する方法を学ぶ必要があるようです。良いデバッガを使用すると、プログラムを1行ずつ実行し、どこからずれているかを確認することができます。これはプログラミングをする場合に不可欠なツールです。詳しい読書:** [小さなプログラムをデバッグする方法](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

+1

代わりに 'i = i + 2'を使います「i + 2」 –

+1

画像としてテキストを投稿しないでください! – Olaf

答えて

3

ループ

for(i=1;i<=t;i+2) 

t >= 1iので、ループで更新されていない場合に無限ループです。 +=+を変更してみてください、代わりに

for(i=1;i<=t;i+=2) 

を使用しています。また、series()の引数がintであるため、の場合はint、関数がmain()の場合はnを使用する必要があります。型の変更時に書式指定子を変更することを忘れないでください。

0

お手数をおかけしていただきありがとうございます。最終的な作業コードは次のとおりです。

#include<stdio.h> 
#include<math.h> 
#include<process.h> 
#include<stdlib.h> 

double series(int,int); 
double factorial(int); 

int main() 
{ 
    int x,n; double res; 
    printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n"); 
    printf("\nPlease enter a value for x and an odd value for n\n"); 
    scanf("%d%d",&x,&n); 
    if(n%2==0) 
    { 
     n=n-1; 
    } 
    res=series(x,n); 
    printf("For the values you've entered, the value of the series is:\n%lf",res); 
} 

double series(int s, int t) 
{ 
    int i,sign=1; double r=0.0,fact,exec; 
    for(i=1;i<=t;i+=2) 
    { 
     exec=sign*(pow(s,i)/factorial(i)); 
     r+=exec; 
     sign*=-1; 
    } 
    return r; 
} 

double factorial(int p) 
{ 
    double f=1; 
    while(p>0) 
    { 
     f*=p; 
     p--; 
    } 
    return f; 
} 
関連する問題