设计函数求一元多项式的导数。(注:xn(n为整数)的一阶导数为nxn−1。)
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是 0,但是表示为 0 0
。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
C:
#include<stdio.h>
int main()
{
int a,b,count=0;
while(scanf("%d %d",&a,&b)!=EOF)
{
if(b==0)
break;
if(count++==0)
printf("%d %d",a*b,b-1);
else
printf(" %d %d",a*b,b-1);
}
if(count==0)
printf("0 0");
return 0;
}
C++:
#include <iostream>
#include <vector>
using namespace std;
void derivative(vector<int>& coefficients, vector<int>& exponents) {
int n = coefficients.size();
for (int i = 0; i < n; i++) {
coefficients[i] *= exponents[i];
exponents[i] -= 1;
}
// 输出导数多项式
for (int i = 0; i < n; i++) {
cout << coefficients[i] << " " << exponents[i];
if (i != n - 1) {
cout << " ";
}
}
}
int main() {
vector<int> coefficients;
vector<int> exponents;
int coefficient, exponent;
while (cin >> coefficient >> exponent) {
coefficients.push_back(coefficient);
exponents.push_back(exponent);
}
derivative(coefficients, exponents);
return 0;
}
Java:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void derivative(List<Integer> coefficients, List<Integer> exponents) {
int n = coefficients.size();
for (int i = 0; i < n; i++) {
coefficients.set(i, coefficients.get(i) * exponents.get(i));
exponents.set(i, exponents.get(i) - 1);
}
// 输出导数多项式
for (int i = 0; i < n; i++) {
System.out.print(coefficients.get(i) + " " + exponents.get(i));
if (i != n - 1) {
System.out.print(" ");
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> coefficients = new ArrayList<>();
List<Integer> exponents = new ArrayList<>();
while (scanner.hasNext()) {
int coefficient = scanner.nextInt();
int exponent = scanner.nextInt();
coefficients.add(coefficient);
exponents.add(exponent);
}
derivative(coefficients, exponents);
}
}
Python:
def derivative(coefficients, exponents):
for i in range(len(coefficients)):
coefficients[i] *= exponents[i]
exponents[i] -= 1
# 输出导数多项式
for i in range(len(coefficients)):
print(coefficients[i], exponents[i], end=' ' if i != len(coefficients) - 1 else '')
coefficients = []
exponents = []
inputs = input().split()
for i in range(0, len(inputs), 2):
coefficients.append(int(inputs[i]))
exponents.append(int(inputs[i + 1]))
derivative(coefficients, exponents)