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
++)
{
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
)));
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!
转载请注明原文地址:https://ipadbbs.8miu.com/read-54316.html