【问题标题】:How to display structures Arrays in functions如何在函数中显示结构数组
【发布时间】:2020-06-11 04:32:33
【问题描述】:

这个程序本质上应该计算随机掷骰子 100 次的结果,并计算每个面的出现次数,然后将它们全部显示为星号的直方图。似乎这些功能可以正常工作,但我无法验证,因为在我做出选择后,什么都没有显示。

#include <iostream>
#include <iomanip>
#include <string>
#include <random>
#include <sstream>
using namespace std;


enum class Side {
  ONE, TWO, THREE, FOUR, FIVE, SIX
};

struct Bar {
  int value;
  Side label;
};


//roll dice function
void rollDice( Bar h[], int n = 100);

void rollDice( Bar h[], int){

default_random_engine en;
uniform_int_distribution<> dist{1,6};

    int results[] ={0,0};

    for( int n; n<=100; n++){
        cout << dist(en);
        results[dist(en)]++;
      h[n].value = results[n];        

      if(h[n].value == 1){
          h[n].label =  Side::ONE;
      }
      else if(h[n].value == 2){
        h[n].label =  Side::TWO;
      }
       else if(h[n].value == 3){
        h[n].label =  Side::THREE;
      }
       else if(h[n].value == 4){
        h[n].label =  Side::FOUR;
      }
       else if(h[n].value == 5){
        h[n].label =  Side::FIVE;
      }
       else {
        h[n].label =  Side::SIX;
      }


    }


};

string getHistogram(Bar h[], char c = '*');

string getHistogram(Bar h[], char c ){

stringstream ast;

    for( int n; n<=100; n++){


          switch (h[n].label)
          {
          case Side::ONE:
              return to_string(c);
            break;
          case Side::TWO:
              return to_string(c);
            break;
          case Side::THREE:
            return to_string(c);
            break;
          case Side::FOUR:
            return to_string(c);
            break;
          case Side::FIVE:
            return to_string(c);
            break;  
          case Side::SIX:
            return to_string(c);
            break;  

          default:
            break;
          }
    }

ast << "One: " << c << endl;
ast << "Two: " << c << endl;
ast << "Three: " << c << endl;
ast << "Four: " << c << endl;
ast << "Five: " << c << endl;
ast << "Six: " << c << endl;

string output = ast.str();

cout<< output;
return output;
}


int main (){

Bar histogram[] = {
  {0,Side::ONE},{0,Side::TWO}, {0,Side::THREE},
  {0,Side::FOUR},{0,Side::FIVE}, {0,Side::SIX}

};

char choice;

do {
  cout << "DICE ROLLING SIMULATION" << endl
       <<"===============================" << endl
       << "r. Roll Dice" << endl
       << "h. Display histogram" << endl
       << "q. Quit program\n" << endl

       << "\nEnter your choice:" << endl;

  // Reading a single character using the scanner
  cin >> choice;



  switch(choice) {
  case 'r': case 'R':
     rollDice(histogram, 100);
    break;
  case 'h': case 'H':
    cout<< getHistogram(histogram, '*');
    break;
  case 'q': case 'Q':
    cout << "Good bye\n" << endl;
    break;
  default:
    cout << "Invalid choice\n" << endl;
  }
} while(choice != 'q');

}

【问题讨论】:

    标签: c++ arrays string random struct


    【解决方案1】:

    所以,这段代码包含许多不同的错误。我们按顺序走吧。

    • 在 structBar 标签可能是 const
    struct Bar {
      int value;
      const Side label;
    };
    
    • 函数签名不需要前向声明
    • rollDice 中有许多不必要的局部变量,我会使用mt19937 随机生成器。所以rollDice 会是这样的
    void rollDice(Bar h[], int count = 100) {
      default_random_engine en;
      uniform_int_distribution<> dist{1,6};
    
      for( int n = 0; n <= count; n++) {
        cout << dist(en) << endl;
        const auto index = dist(en) - 1;
        ++h[index].value;
      }
    };
    
    • getHistogram 你有return to_string(c); 在开关因此你看不到直方图。你可以删除swith,因为你可以匹配索引和Side。为什么要循环多达 100 个?
    string getHistogram(Bar h[], char c = '*') {
      stringstream ast;
      for( int n = 0; n <= 5; n++) {
        const string strValue = string(h[n].value, c);
    
        switch (h[n].label)
        {
        case Side::ONE:   ast << "One:   "; break;
        case Side::TWO:   ast << "Two:   "; break;
        case Side::THREE: ast << "Three: "; break;
        case Side::FOUR:  ast << "Four:  "; break;
        case Side::FIVE:  ast << "Five:  "; break;
        case Side::SIX:   ast << "Six:   "; break;
        }
    
         ast << strValue << '(' << h[n].value << ')' << endl;
      }
    
      return ast.str();
    }
    
    • main 函数中,您必须在下一个rollDice 之前清除直方图
    case 'r': case 'R':
          for (Bar& b : histogram) {
            b.value = 0;
          }
          rollDice(histogram, 100);
          break;
    

    完整版

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <random>
    #include <sstream>
    using namespace std;
    
    enum class Side {
      ONE, TWO, THREE, FOUR, FIVE, SIX
    };
    
    struct Bar {
      int value;
      Side label;
    };
    
    void rollDice(Bar h[], int count = 100) {
      default_random_engine en;
      uniform_int_distribution<> dist{1,6};
    
      for( int n = 0; n <= count; n++) {
        cout << dist(en) << endl;
        const auto index = dist(en) - 1;
        ++h[index].value;
      }
    };
    
    string getHistogram(Bar h[], char c = '*') {
      stringstream ast;
      for( int n = 0; n <= 5; n++) {
        const string strValue = string(h[n].value, c);
    
        switch (h[n].label)
        {
        case Side::ONE:   ast << "One:   "; break;
        case Side::TWO:   ast << "Two:   "; break;
        case Side::THREE: ast << "Three: "; break;
        case Side::FOUR:  ast << "Four:  "; break;
        case Side::FIVE:  ast << "Five:  "; break;
        case Side::SIX:   ast << "Six:   "; break;
        }
    
         ast << strValue << '(' << h[n].value << ')' << endl;
      }
    
      return ast.str();
    }
    
    
    int main (){
      Bar histogram[] = {
        {0, Side::ONE},
        {0, Side::TWO},
        {0, Side::THREE},
        {0, Side::FOUR},
        {0, Side::FIVE},
        {0, Side::SIX}
      };
    
      char choice;
      do {
        cout << "DICE ROLLING SIMULATION" << endl
             <<"===============================" << endl
            << "r. Roll Dice" << endl
            << "h. Display histogram" << endl
            << "q. Quit program\n" << endl
    
            << "\nEnter your choice:" << endl;
    
        // Reading a single character using the scanner
        cin >> choice;
    
        switch(choice) {
        case 'r': case 'R':
          for (Bar& b : histogram) {
            b.value = 0;
          }
          rollDice(histogram, 100);
          break;
        case 'h': case 'H':
          cout << getHistogram(histogram, '*') << endl;
          break;
        case 'q': case 'Q':
          cout << "Good bye\n" << endl;
          break;
        default:
          cout << "Invalid choice\n" << endl;
        }
      } while(choice != 'q');
    }
    

    【讨论】:

    • 我上面的代码是由一些规则定义的,目的是为了分配任务和我们在课程中的位置。这些是提供的步骤:编写一个 C++ 程序,该程序模拟 100 个骰子的滚动,并将 1、2、3、4、5 和 6 的数量存储在一个数组中。然后它将结果打印为 6 个柱状图的直方图,每边一个柱状图。请按照以下步骤操作:在程序顶部添加以下范围枚举和结构(枚举类 Side { ONE, TWO, THREE, FOUR, FIVE, SIX }; struct Bar { int value; Side label; };)跨度>
    • 2.定义一个名为rollDice()的函数,原型如下: void rollDice(Bar h[], int n = 100); 3. 该函数使用 头文件的default_random_engine 和uniform_int_distribution 工具来模拟100 个骰子的滚动。发生了多少 1、2、3、4、5 和 6 的计数被保存到数组 h 的每个 bar 元素的 value 成员中。使用以下原型定义一个名为 getHistogram() 的函数: string getHistogram(Bar h[], char c = '*');
    • 3.此函数应使用 头文件中的 stringstream 来构建并返回包含直方图的字符串,其格式类似于以下内容。一:***************(15)二:*********************(22)三:* *************** (16) 四:****************** (16) 五:********* ***** (14) 六: ***************** (17) 这个函数有两个参数,第一个是由rollDice()更新的直方图数组函数,第二个是用于显示条的字符符号('*' 应该用作默认参数)。
    • 4.在main()函数中:定义一个由六个Bar结构组成的数组,命名为histogram。初始化此数组,使每个柱都有正确的边(Side::ONE、Side::TWO 等),值为 0。在 do-while 循环中,程序应继续显示以下菜单:DICE ROLLING SIMULATION ====================== r。掷骰子 h.显示直方图 q。退出程序 输入您的选择:在掷骰子之前输入 h 应该在空直方图上调用函数 getHistogram() 打印以下内容:
    • @ChadrickHollingsworth 看这里 string 示例 2。这将创建一个字符串 c 和一个长 h[n].value。例如string(5, '*') 返回*****
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2021-07-15
    相关资源
    最近更新 更多