2007년 04월 05일
다항식 입력받아 지수,계수 분리하기.
///////// 굴하지 않고 string.h따위는 살짝 씹어주고 if노가다를 해주는 센스
///////// Edited by Muzie.
///////// 혹시라도 이 프로그램을 학교 과제를 위해 이용한다면 놀림을 당할거란건 당연지사.
///////// 지수든 계수든 한자리라는 것을 가정, 지수는 음수가 안되지만 계수는 음수 가능.
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
void main()
{
char str[MAX]; // 입력받은 문자열을 저장할 공간.
// int coeftemp; // 계수를 임시로 저장할 변수.
// int expontemp; // 지수를 임시로 저장할 변수.
int cnt; // 루프를 돌리기 위한 변수.
int coef[MAX],expon[MAX],loo=0,loo2=0;
scanf("%s",str); // 입력을 받는다.
for(cnt=0;str[cnt]!=NULL;cnt++) // NULL이 아닐때까지 배열에 있는 스트링을 빼낸다.
{
if(cnt==0&&str[cnt]=='-'&&str[cnt+1]=='x') {coef[loo] = -1 ; cnt++; loo++;}// 만약 배열의 처음이고 '-'가 붙어있으면
if(cnt==0&&str[cnt]=='-') {coef[loo] = ((int)str[cnt+1]-48)*-1 ; cnt++; loo++;}// 만약 배열의 처음이고 '-'가 붙어있으면
if(cnt==0&&(int)str[cnt]>=48&&(int)str[cnt]<=57) { coef[loo]= (int)str[cnt]-48; loo++; }// 만약 배열의 처음이고 cnt가 숫자의 범위에 들어와있으면 계수이다.
if(str[cnt]=='x') {if(str[cnt-1]=='+'||cnt==0) {coef[loo]= 1; loo++;}//만약 x 이전이 +이면 계수는 1.
if(str[cnt-1]=='-'&&cnt-1 != 0) {coef[loo] = -1; loo++;}//만약 x 이전이 -이면 계수는 -1.
if(str[cnt+1]=='^') // 만약 x가 나오고 바로뒤가 ^이면 지수가 2 이상이다.
{cnt ++; continue;}
if(str[cnt+1]=='+'||str[cnt+1]=='-'||str[cnt+1]==NULL) {expon[loo2]=1; loo2++;continue;}
} // x뒤에 ^ 없으면 지수가 1이다.
if((int)str[cnt]>=48&&(int)str[cnt]<=57&&str[cnt-1]=='^'){ // 숫자범위이고 이전 스트링에 ^가 있으면 그놈은 계수다.
expon[loo2] = (int)str[cnt]-48;
loo2++;}
if((int)str[cnt]>=48&&(int)str[cnt]<=57&&str[cnt+1]=='x'&&str[cnt-1]=='+'&&cnt!=0&&cnt-1!=0) { coef[loo] =(int)str[cnt]-48; loo++;}
if((int)str[cnt]>=48&&(int)str[cnt]<=57&&str[cnt+1]=='x'&&str[cnt-1]=='-'&&cnt!=0&&cnt-1!=0) { coef[loo] =((int)str[cnt]-48)*-1; loo++;}
if(str[cnt-1]=='+'&&(int)str[cnt]>=48&&(int)str[cnt]<=57&&str[cnt+1]==NULL) { coef[loo] = (int)str[cnt]-48; expon[loo2]=0; loo2++; loo++; }
if(str[cnt-1]=='-'&&(int)str[cnt]>=48&&(int)str[cnt]<=57&&str[cnt+1]==NULL) { coef[loo] = ((int)str[cnt]-48)* (-1); expon[loo2]=0; loo++; loo2++;}
}
for(cnt=0;cnt<loo;cnt++)
printf("coef = %d expon = %d\n",coef[cnt],expon[cnt]);
}

# by | 2007/04/05 23:13 | STUDY | 트랙백 | 덧글(0)




☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]