标签:
题目:给定一个数组A[0,1,2...N-1],请构建一个数组B[0,1,2,...N-1],使B中的元素B[i]=A[0]*A[1]*...*A[i-1]*a[i+1]*...*a[n-1],不能使用除法。#include <iostream> using namespace std; #include <vector> vector<int> array1; vector<int> array2(5); void multiply(const vector<int> &array1,vector<int> &array2) { int length1=array1.size(); int length2=array2.size(); if(length1==length2 && length2>1) { array2[0]=1; for(int i=1;i<length1;i++) { array2[i]=array2[i-1]*array1[i-1]; } double temp=1; for(int i=length1-2;i>=0;i--) { temp*=array1[i+1]; array2[i]*=temp; } } } int main() { for(int i=0;i<5;i++) array1.push_back(i+1); multiply(array1,array2); vector<int>::iterator it1; vector<int>::iterator it2; cout<<"A数组为:"; for(it1=array1.begin();it1!=array1.end();it1++) cout<<*it1<<" "; cout<<endl; cout<<"B数组为:"; for(it2=array2.begin();it2!=array2.end();it2++) cout<<*it2<<" "; cout<<endl; system("pause"); return 0; }
主要是利用中间结果变量。运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51775781