首页 > 解决方案 > c ++类似的重复输入具有不同的输出

问题描述

#include<iostream>
#include "cmath"
using namespace std;

double power(double a1, double b2)
{
    double result;
    result = pow(a1,b2);
    return result;
}

int main()
{
    int a1, b2, result;
    int choice = 0;
    int count = 4;
    int r1,r2,r3,r4;

    while (choice < count)
    {
        cout <<"Enter the value of coefficient." << endl
        << "Coefficient: ";
        cin >> a1;

        cout <<"Enter the value of the exponent." << endl << "Exponent: ";
        cin >> b2;
        choice++;
    }

    if (a1 == 0 && b2 == 0)
    {
        cout << "You entered 0 values. " << endl;
    }
    else
    {
        r1 = power(a1,b2);
        r2 = power(a1,b2);
        r3 = power(a1,b2);
        r4 = power(a1,b2);
    
        cout << "The answers are: " << endl
        << r1 << endl << r2 << endl << r3 << endl << r4 << endl;
    }
    return 0;
}

我需要显示不同的输出值,但它只给了我完成的最后一次输入计算。那么我怎么可能显示那些第一个/第二个值呢?初学者在这里,所以我愿意接受一些批评。

标签: c++

解决方案


我不确定你想做什么,但我假设你想问 8 个数字(4 次 a 和 4 次 b)。并且您想显示 4 个结果 ( r1, r2... )。但是当你第二次 请求时a,你只是用新值覆盖它们,当你这样做时bcin >> a1;

对于您正在做的事情,我鼓励您了解数组

因此,您可能应该在覆盖它们之前进行数学运算,并将结果存储在数组中:

// declare the array of size 4

int resultArray[4];
...
...
cin >> b2;
r1 = power(a1,b2);
resultArray[choice] = r1
choice++;
}

cout << "First result :" << resultArray[0]

或者您可以暂时存储您的值,然后进行数学运算

// declare 2 arrays of size 4

int coefficientArray[4];
int exponentArray[4];

...

cin >> b2;
coefficientArray[choice] = a1;
exponentArray[choice] = b2;
choice++;
}

...

r1 = power(coefficientArray[0],exponentArray[0]);
r2 = power(coefficientArray[1],exponentArray[1]);


推荐阅读