2016-08-16 5 views
0

x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ... (x^n/n)을 계산하는 프로그램을 작성하고 싶습니다. !) 사용자 입력으로 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++ 솔루션도 좋습니다.

Output window in code::blocks

+3

Welcome to Stack Overflow! 디버거를 사용하여 코드를 단계별로 실행하는 방법을 배워야 할 필요가있는 것 같습니다. 좋은 디버거를 사용하면 한 줄씩 프로그램을 실행하고 예상 한 곳에서 벗어난 곳을 볼 수 있습니다. 프로그래밍을 할 때 필수적인 도구입니다. 추가 읽기 : ** [작은 프로그램을 디버깅하는 방법] (http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) ** – NathanOliver

+1

대신'i = i + 2'를 사용하십시오. of i + 2' –

+1

텍스트를 이미지로 게시하지 마십시오! – Olaf

답변

3

함수 series()에서 루프

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

t >= 1i 때문에 루프가 업데이트되지 무한 루프이다. +=+를 변경 시도하고 대신

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

를 사용합니다. 또한 series()의 인수가 int이므로 main() 함수에 xnint 유형을 사용해야합니다. 유형을 변경할 때 형식 지정자를 변경하는 것을 잊지 마십시오.

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; 
} 
관련 문제