1. 程式人生 > 其它 >PAT甲級 1002 A+B for Polynomials (25 分) -- setiosflags( )的用法

PAT甲級 1002 A+B for Polynomials (25 分) -- setiosflags( )的用法

技術標籤:PAT甲級

先粘題 原題連結:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

1002 A+B for Polynomials (25 分)

This time, you are supposed to findA+BwhereAandBare two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

KN​1​​a​N​1​​​​N​2​​a​N​2​​​​...N​K​​a​N​K​​​​

whereKis the number of nonzero terms in the polynomial,N​i​​anda​N​i​​​​(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤1000.

Output Specification:

For each test case you should output the sum ofAandBin one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

分析 :

讀題 給兩個多項式進行求和運算 開頭第一個數字k代表項數 然後 指數1 係數1 指數2 係數2按照指數遞減的方式排列 我們可以用map 陣列 或者結構體來做 對比三種方法 發現還是陣列最簡單

易錯點 :

1 注意係數可以為負數

2 浮點數要四捨五入保留一位小數!

程式碼:

#include <iostream>
#include <iomanip>
using namespace std;

const int N = 10010;
double a[N];
int main(){
    int sum=0,x,m;
    double y;
    cin.tie();
    cin>>m;
    while(m--){
        cin>>x>>y;
        a[x] += y;
    }
    cin>>m;
    while(m--){
        cin>>x>>y;
        a[x] += y;
    }
     for(int i=N-1;i>=0;i--){
        if(a[i]!=0) sum++;
    }
    cout<<sum;
    for(int i = N; i >= 0; i--){
		if(a[i] != 0){
			cout<<" "<<i<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<a[i];
            //printf(" %d %.1f",i,a[i]);
		}
	}

}

知識點 :

1. setprecision( )

使用setprecision(n)可控制輸出流顯示浮點數的數字個數。C++預設的流輸出數值有效位是6setprecision(n)就是輸出n個數,會有四捨五入。

2. setiosflags(ios::fixed)

setprecision(n)setiosflags(ios::fixed)合用,可以控制小數點右邊的數字個數。