PAT基礎編程題目-6-2 多項式求值

PAT基礎編程題目-6-2 多項式求值

題目詳情

在這裏插入圖片描述

【題目地址】:https://pintia.cn/problem-sets/14/problems/734

解答

C語言版

#include <stdio.h>

#define MAXN 10

double f(int n, double a[], double x);

int main()
{
	int n, i;
	double a[MAXN], x;

	scanf("%d %lf", &n, &x);
	for (i = 0; i <= n; i++)
		scanf("%lf", &a[i]);
	printf("%.1f\n", f(n, a, x));
	return 0;
}

double f(int n, double a[], double x) {
	double sum = 0;
	double y = 1;
	for (int i = 0; i <= n; i++)
	{
		for (int j = 0; j < i; j++)
		{
			y = x * y;
			break;
		}
		sum = sum + a[i] * y;
	}
	return sum;
}

在這裏插入圖片描述

C++版

#include <iostream>
#include <iomanip>
using namespace std;
#define MAXN 10
double f(int n, double a[], double x);
int main()
{
	int n;
	double a[MAXN], x;
	cin >> n >> x;
	for (int i = 0; i <= n; i++)
	{
		cin >> a[i];
	}
	cout <<fixed<<setprecision(1)<<f(n, a, x);   // 以固定浮點位顯示,且以一位小數顯示
	return 0;
}
double f(int n, double a[], double x) {
	double sum = 0;
	double y = 1;
	for (int i = 0; i <= n; i++)
	{
		//for (int j = 0; j < i; j++)
		//{
		//	y = x * y;
		//	break;  // 每次多乘一個x就可以了
		//}
		if (i > 0) 
			y = x * y;
		sum = sum + a[i] * y;
	}
	return sum;
}

在這裏插入圖片描述

Java版

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {

	private static final int MAXN = 10;
	
	private static double f(int n, double [] a, double x) {
		double sum = 0;
		double y = 1;
		for (int i = 0; i <= n; i++) {
			if( i > 0 )
				y = x*y;
			sum = sum + a[i]*y;
		}
		return sum;
	}
	
	public static void main(String[] args) {
		int n = 0;
		double [] a = new double[MAXN];  //定義數組的方式
		double x = 0;
		Scanner scanner = new Scanner(System.in);
		if(scanner.hasNext()) {
			n = scanner.nextInt();
			x = scanner.nextDouble();
			for (int i = 0; i <= n; i++) {
				a[i] = scanner.nextDouble();
			}
		}
		scanner.close();
		DecimalFormat decimalFormat = new DecimalFormat("#.0"); //保留小數點後一位
		System.out.println(decimalFormat.format(f(n, a, x)));
	}

}

在這裏插入圖片描述

創作不易,喜歡的話加個關注點個贊,謝謝謝謝謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章