求条!

P1067 [NOIP2009 普及组] 多项式输出

AndyCGM @ 2024-10-24 16:00:09

#include <bits/stdc++.h>
using namespace std;
int s[10000];
int main(){
    int n;
    cin >> n;
    for (int i=1; i<=n+1; i++){
        cin >> s[i];
    }
    for (int i=1; i<=n+1; i++){
        //符号
        if (i!=1){
            if (s[i]==0)    continue;
            if (abs(s[i])==s[i]) cout << "+";
            else    cout << "-";
        }
        if (i==1){
            if (abs(s[i])!=s[i]){
                cout << "-";
            }
        }
        //数值
        if (abs(s[i])!=1)   cout << abs(s[i]);
        if (i==n+1 || abs(s[i])==1) cout << 1;
        //次数
        if (i==n+1) continue;
        cout << "x^" << n+1-i;
    }
}

by chengenzhen @ 2024-10-24 16:28:14

@AndyCGM 幂次为1需要省略,倒数第二个if改成与运算,第13行的代码需要放在if外面实现如下

#include <bits/stdc++.h>
using namespace std;
int f=1,s[10000];
int main(){
    int n;
    cin >> n;
    for (int i=1; i<=n+1; i++){
        cin >> s[i];
    }
    for (int i=1; i<=n+1; i++){
        //符号
        if (s[i]==0)    continue;
        if (f!=1){
            if (abs(s[i])==s[i]) cout << "+";
            else    cout << "-";
        }
        if (f==1){
            f=0;
            if (abs(s[i])!=s[i]){
                cout << "-";
            }
        }
        //数值
        if (abs(s[i])!=1)   cout << abs(s[i]);
        if (i==n+1 && abs(s[i])==1) cout << 1;
        //次数
        if (i==n+1) continue;
        if(i!=n)cout << "x^" << n+1-i;
        else cout<<"x";
    }
}

by AndyCGM @ 2024-10-24 16:43:04

@chengenzhen thanks


|