题目地址:http://poj.org/problem?id=1555
思路:注意都是0的情况输出是0,不能通过加和判断是否所有的数都为0,虽然会AC,这是数据问题,狂测的时候测出来的BUG,给个例子啊
0 0 1 -1 0 0 0 0 0 虽然和为0,但是数据输出不应该是0
AC代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> const int inf = 0x3f3f3f3f;//1061109567 typedef long long LL; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; int a[10]; void solove() { bool flag = true; int k; for(k=0; k<9; k++) { if(a[k] != 0) break; } if(k == 9) printf("0"); for(int i=0; i<9; i++) { if(a[i] == 0) continue; if(flag) { if((a[i] != 1 && a[i] != -1 )|| i == 8) { printf("%d",a[i]); } if(i == 7) { if(a[i] == -1) printf("-x"); else printf("x"); } else if(i == 8); else { if(a[i] == -1) printf("-x^%d",8-i); else printf("x^%d",8-i); } flag =false; } else { if(a[i] > 0) { printf(" + "); } else { printf(" - "); a[i] = abs(a[i]); } if(a[i] != 1 || i == 8) printf("%d",a[i]); if(i == 7) printf("x"); else if(i == 8); else printf("x^%d",8-i); } } printf("\n"); } int main() { while(cin>>a[0]>>a[1]>>a[2]>>a[3]>>a[4]>>a[5]>>a[6]>>a[7]>>a[8]) { solove(); } return 0; }错误代码:
(逻辑没有一点问题,输入数据的时候出错了,不知道哪错了)
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> const int inf = 0x3f3f3f3f;//1061109567 typedef long long LL; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; int a[10]; void solove() { bool flag = true; int k; int sum = 0; for(k=0; k<9; k++) { sum += a[k]; } if(sum == 0) printf("0"); for(int i=0; i<9; i++) { if(a[i] == 0) continue; if(flag) { if((a[i] != 1 && a[i] != -1 )|| i == 8) { printf("%d",a[i]); } if(i == 7) { if(a[i] == -1) printf("-x"); else printf("x"); } else if(i == 8); else { if(a[i] == -1) printf("-x^%d",8-i); else printf("x^%d",8-i); } flag =false; } else { if(a[i] > 0) { printf(" + "); } else { printf(" - "); a[i] = abs(a[i]); } if(a[i] != 1 || i == 8) printf("%d",a[i]); if(i == 7) printf("x"); else if(i == 8); else printf("x^%d",8-i); } } printf("\n"); } int main() { int b,k = 0; char c; while(scanf("%d%c",&b,&c) != EOF) { a[k++] = b; if(c == '\n') { solove(); k = 0; } } return 0; }