变量定义,初学者协助

时间:2019-04-03 22:23:28

标签: c++

难以理解整数n和k在raiseToPower函数中的用途。通常在定义函数时。我知道当它被调用时它如何以某种方式暂停主函数,但是变量n和k如何成为其中的一个因数?

#include <iostream> using namespace std; #include "simpio.h" #include <string> int raiseToPower(int n, int k); //This created a variable called raiseToPower //It has 2 integers that it can call upon, n and k //This makes it possible for the function to be used without a definiton in the main int main(){ //Indicates main is a integer int limit; //Limit is now a variable that can hold integers cout << "This program lists powers of two." << endl; //Tell the user that this is what the program does cout << "Enter exponent limit: "; //No endl, so that the user can input something cin >> limit; //This lets the user input a integer, and store it in limit for (int i = 0; i <= limit; i++) { //creates a for loop that will do the action till it completes its work //While i = 0, and it is less then or equal to limit, add 1 to i cout << "2 to the " << i << " = " << raiseToPower(2, i) << endl; } return 0; } int raiseToPower(int n, int k) { //creates variablee result that holds a integers, and in this case 1 int result = 1; // a for loop so that the for (int i=0; i < k; i++) { result *= n; } return result; }

我的大部分问题都在上面的部分中。函数定义。我不明白在这里使用n和k的地方

1 个答案:

答案 0 :(得分:1)

raiseToPower是一个返回值的函数。

nk是传递给raiseToPower函数的整数参数。 n被提升到k的位置。

为此,该函数通过从0到n-1循环,仅将k自身k的倍数乘以result *= n 。这是通过

行完成的
result = result * n.

也可以写为

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint- 
 layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 
'com.android.support.test.espresso:espresso-core:3.0.2'
相关问题