现在的位置: 首页 > 综合 > 正文

(数组的应用三:多项式的表示与处理4.3.1)POJ 1555 Polynomial Showdown(多项式的输出)

2013年12月13日 ⁄ 综合 ⁄ 共 726字 ⁄ 字号 评论关闭
/*
 * poj_1555.cpp
 *
 *  Created on: 2013年10月25日
 *      Author: Administrator
 */

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

const int n = 9;//指数由8~0是有9个数字的
int main(){
	int a[n];

	while(scanf("%d",&a[0])!=EOF){//不要漏了EOF,否则会OLE。。要是用多种测试用例尽量将程序写成能处理多个测试样例的程序...否则就算逻辑正确也很可能WA
		int i;
			for(i = 1 ; i < n ; ++i){
				scanf("%d",&a[i]);
			}

			bool first = true;

			for(i = 0 ; i < n ; ++i){
				if(a[i]){//按照指数由高到低输出非0项
					if(first){//处理首项
						if(a[i] == -1 && i < n - 1){
							cout<<"-";
						}else if(a[i] != 1 || i == n - 1){
							cout<<a[i];
						}

						if(i == n - 2){
							cout<<"x";
						}else if(i < n - 1){
							cout<<"x^"<<n - i - 1;
						}

						first = false;
					}else{
						cout<<" "<<(a[i] < 0 ? "-":"+")<<" ";

						if(abs(a[i]) != 1 || i == n - 1){
							cout<<abs(a[i]);
						}

						if(i == n-2){
							cout<<"x";
						}else if(i < n - 1){
							cout<<"x^"<<n-i-1;
						}

					}
				}
			}

			if(first){//如所有系数都为0,则输出0
				cout<<"0";
			}

			cout<<endl;
	}

	return 0;
}

抱歉!评论已关闭.