如何使用循环来增加指数?

时间:2018-11-28 02:39:17

标签: c++ loops

我想使用循环增加指数。例如,X是指数开始的数字,Y是指数结束的数字。 Z是基数。 因此,如果输入是:

  

X = 1 Y = 6 Z = 2

输出将为

  

2 4 6 8 16 32 64

#include <iostream>
using namespace std;
int main()

{
    int x,y,z;

    cout<<"X = ";
    cin>>x;

    cout<<"Y = ";
    cin>>y;

    cout<<"Z = ";
    cin>>z;

    for(z=z;z<=z;z){

        for(x=x;x<=y;x++){

        }
    }
    return 0;
}

那是我能做的。我应该在循环部分做什么?

3 个答案:

答案 0 :(得分:1)

您需要遍历从下限(x)到上限(y)的指数,并执行z ^ n运算,其中(n> = x和n <= y)。请参阅下面的代码,为便于阅读,我将x重命名为start,将y重命名为base,将z重命名为base。不要忘了包括math.h。

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int start, finish, base;

    cout << "Start: ";
    cin >> start;
    cout << "Finish: ";
    cin >> finish;
    cout << "Base: ";
    cin >> base;

    // start at lower bound, increase n by 1
    // until n is equal to upper bound
    for(int n = start; n <= finish; n++) {
        cout << base << "^" << n << " = " << pow(base, n) << endl;
    }

    return 0;
}

答案 1 :(得分:1)

前一种解决方案的缺点是每次迭代都计算pow(base, exponent)
通过迭代计算结果获得的操作更少了

#include <iostream>
#include <cmath>
using namespace std;
int main()

{
    int first, last, base;

    cout << "first = ";
    cin >> first;
    cout << "last = ";
    cin >> last;
    cout << "base = ";
    cin >> base;


    int result = pow (base, first);

    for(int exponent = first; exponent <= last; ++exponent){
        cout << base << "^" << exponent << " = " << result << "\n";
        result *= base;
    }
    return 0;
}

答案 2 :(得分:0)

for(int i = x; i <= y; i++) {
    int pow_num = pow(z,i); // This is what you have to do.
}

还要注意,对于较大的y,您会看到integer overflow。您必须照顾好这一点。