【问题标题】:Calling Function not Displaying Results调用函数不显示结果
【发布时间】:2017-10-19 09:45:53
【问题描述】:

我通过以下方式使用随机数创建5 x 5array

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main () {
    int a[5][5];
    int randomNumber;
    srand (time(NULL));
    // output each array element's value                      
    for ( int i = 0; i < 5; i++ ) {
          cout << endl;
        for ( int j = 0; j < 5; j++ ) {
             a[i][j] = randomNumber;
             randomNumber = rand() %100 + 1;
             cout << a[i][j] << "  ";
        }
       cout << endl;
    }
  return 0;
} 

它的输出在 5 x 5 Array 下面给出。

但是当我将循环包装到一个函数中然后调用它时。然后它没有显示任何结果。

#include <iostream>
#include <stdlib.h> 
#include <time.h>
using namespace std;

int main () {

   // output each array element's value   
   cout <<"Array Results are.....";
   int PopulateArray();                   

  return 0;
}

int PopulateArray(){
int a[5][5];
int randomNumber;
srand (time(NULL));

for ( int i = 0; i < 5; i++ ) {

       cout << endl;

    for ( int j = 0; j < 5; j++ ) {
        a[i][j] = randomNumber;
        randomNumber = rand() %100 + 1;
        cout << a[i][j] << "  ";
      }
    cout << endl;
  }
}

现在结果是这样的

问题

当我将loop 包裹在function 中时,为什么没有显示结果?

【问题讨论】:

    标签: c++ function loops functional-programming


    【解决方案1】:

    您的main 函数永远不会调用PopulateArrayint PopulateArray(); 行声明了它没有调用它的函数。

    【讨论】:

      【解决方案2】:

      您错误地调用了该函数。您的代码中的这一行:

      int PopulateArray(); 
      

      并没有真正调用该函数,它只是声明它。所以程序所做的只是将文本打印到 cout,然后它声明一个函数而不执行它,然后退出。正确的调用方式只是:

      PopulateArray(); 
      

      顺便说一句,这个函数没有理由返回一个 int,因为它没有返回整数。

      【讨论】:

        猜你喜欢
        • 2021-09-04
        • 2021-06-16
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 2021-01-16
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        相关资源
        最近更新 更多