如何输入多个动态数组整数?

时间:2015-12-02 06:12:49

标签: arrays loops dynamic polynomials

如何修改此代码,以便输入多个系数?

我想能够输入类似“3 2 1”的东西,这些空格不应该影响我的用户输入,但我不知道该怎么做。

这是我到目前为止的代码:

#include <iostream>
using namespace std;

int *foil(int A[], int B[], int co, int coo)
{
   int *product = new int[co+coo-1];

   for (int i = 0; i<co+coo-1; i++)
     product[i] = 0;

   for (int i=0; i<coo; i++)
   {
     for (int j=0; j<co; j++)
         product[i+j] += A[i]*B[j];
   }

   return product;
}

void printPoly(int poly[], int co)
{
    for (int i=0; i<co; i++)
    {
       cout << poly[i];
       if (i != 0)
        cout << "x^" << i ;
       if (i != co-1)
       cout << " + ";
    }
}


int main()
{
    int co, coo;

    int *A;
    A=new int[co];

    int *B;
    B=new int[coo];



    cout << "How many coefficients are in the first poly?: ";
    cin >> co;

    cout << "What are the coefficients? (Lowest power first): ";
    cin >> *A;

    cout << "How many coefficients are in the second poly?: "; 
    cin >>coo;

    cout << "What are the coefficients? (Lowest power first): ";
    cin >>*B;

    printPoly(A, coo);
    cout << "\n";
    cout << "times" << endl;
    printPoly(B, co);
    cout << "\n";
    cout << "-----" << endl;
    int *product = foil(A, B, co, coo);
    printPoly(product, co+coo-1);

    return 0;
}

输出:

How many coefficients are in the first poly?: 3
What are the coefficients? (Lowest power first): 3 2 1
How many coefficients are in the second poly?: What are the coefficients? (Lowest power first): 3 + 0x^1
times
1 + 0x1 + 0x^2
-----
3 + 0x^1 + 0x^2 + 0x^3

我希望它像这样输出:

How many coefficients are in the first poly?: 3
What are the coefficients? (Lowest power first): 3 2 1
How many coefficients are in the second poly? 3
What are the coefficients? (Lowest power first): 1 2 1
3 + 2x^1 + 1x^2 
times 
1 + 2x^1 + 1x^2 
-----­­­­­ 
3 + 8x^1 + 8x^2 + 4x^3 + 1x^4

1 个答案:

答案 0 :(得分:1)

你需要在循环中获取输入。 这是你如何做到的。

cout << "How many coefficients are in the first poly?: ";
    cin >> co;

    cout << "What are the coefficients? (Lowest power first): ";
    for(int i=0;i<co;i++)
    cin >> *(A+i);

    cout << "How many coefficients are in the second poly?: ";

    cin >>coo;

    cout << "What are the coefficients? (Lowest power first): ";
    for(int i=0;i<coo;i++)
    cin >>*(B+i);

    printPoly(A, coo);
    cout << "\n";
    cout << "times" << endl;
    printPoly(B, co);
    cout << "\n";
    cout << "-----" << endl;
    int *product = foil(A, B, co, coo);
    printPoly(product, co+coo-1);

    getch();
    return 0;

这是输出图像enter image description here