在C ++循环中显示功能

时间:2016-09-02 06:09:42

标签: c++ loops

我必须解决以下练习

  

编写一个程序,以显示1,5,25,125到n个术语。

我上11年级,我尝试了很多方法来编写这个程序 控制变量的值是1,它小于n 但它应该有多少不同,以便它服从上述问题?
如果你能用简单的语言,请回答 我还应该使用特殊变量来获得电源吗?

提前致谢,Abhijith

5 个答案:

答案 0 :(得分:3)

打印旧值乘以5,从1

开始

基本样机:

auto PrintExercise(std::size_t terms) -> void {
    std::size_t lastResult = 1;
    for (std::size_t i = 0; i < terms; ++i) {
        std::cout << std::to_string(lastResult) << std::endl;
        lastResult *= 5;
    }
}

编辑:事实证明我推翻了这一点。只打印控制变量的功能会更容易。

auto PrintExercise(std::size_t terms) -> void {
    for (std::size_t i = 0; i < terms; ++i) {
        std::cout << std::to_string(pow(5,n)) << std::endl;
    }
}

答案 1 :(得分:3)

由于已经提供了正确的答案,所以这里使用递归而不是迭代(循环)的方法与(希望)足够的注释来解释该过程。只是为了完整。试一试,这很有趣!

#include <iostream>

//value = the value that will be printed
//end = after how many iterations you want to stop
void PowerOfFive( const int value, const int end )
{
    //Print the current value to the console. This is more or
    //less everything the function does...
    std::cout << value << ", ";

    //... but a function can also call itself, with slightly different
    //values in this case. We decrement "end" by 1 and let the whole 
    //process stop after "end" reaches 0. As long as we're doing that,
    //we're multiplying "value" by five each time.
    if ( end != 0 )
    {
        PowerOfFive( value * 5, end - 1 );
    }
}


int main()
{
    //Example for the above
    //Start: 
    //      1st PowerOfFive(1, 3)
    //          --> prints 1
    //          --> calls 2nd PowerOfFive(1 * 5, 3 - 1)
    //                  --> prints 5
    //                  --> calls 3rd PowerOfFive(5 * 5, 2 - 1)
    //                          --> prints 25
    //                          --> calls 4th PowerOfFive(25 * 5, 1 - 1)
    //                                  --> prints 125
    //                                  --> function 4 ends because "end" has reached 0
    //                          --> function 3 ends
    //                  --> function 2 ends
    //          --> function 1 ends
    PowerOfFive( 1, 3 );

    getchar( );
    return 0;
}

答案 2 :(得分:1)

似乎你想要打印5到n的幂,不确定控制变量是什么意思。所以这应该有用

for (int i=0;i<=n;++i) cout << pow(5,i) << ", " ;

答案 3 :(得分:1)

迭代值为5,可以使用pow()函数和&amp ;;也可以像这样使用简单的for循环。

power=0;
cout<<power; 
for(i=0;i<n;i++)
{
 power=power*5;  // OR power*=5
}
cout<<power;

答案 4 :(得分:0)

我添加代码看看是否有帮助

        #include<iostream>
        #include <cmath>
        using namespace std;
        int main() 
        {
        int exp;
        float base;
        cout << "Enter base and exponent respectively:  ";
        cin >> base >> exp;
        for(int i=0;i<exp;i++)
        {
        cout << "Result = " << pow(base, i);
        } 
        return 0;
        }

你必须传递基数和指数值,对于你的问题,它应该是base = 5和exp = 3,你的输出将是1,5,25