我必须解决以下问题
编写程序显示1,5,25,125至n项。
我在11年级,我已经尝试了很多方法来编写这个程序。
控制变量的值为1,且小于n。
但是它应该相差多少才符合上面的问题呢?
请尽量用简单的语言回答。
我还应该用一个特殊的变量来表示功率吗?
提前感谢,Abhijith
打印旧值乘以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;
}
}
既然已经提供了正确的答案,这里是使用递归而不是迭代(循环)的相同方法,并(希望)有足够的注释来解释该过程。只是为了完整。试试吧,很有趣的!
#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;
}
似乎你想打印5到n的权力,不确定你的控制变量是什么意思。这应该行得通
for (int i=0;i<=n;++i) cout << pow(5,i) << ", " ;
迭代值为5,可使用pow()函数&也可以像这样使用简单的for循环。
power=0;
cout<<power;
for(i=0;i<n;i++)
{
power=power*5; // OR power*=5
}
cout<<power;
我正在添加代码,看看是否有帮助
#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