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)));
	}

}

创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!

全部评论

相关推荐

贪食滴🐶:你说熟悉扣篮的底层原理,有过隔扣职业球员的实战经验吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务