c ++规范化一个数组

时间:2016-02-22 14:14:20

标签: c++ arrays normalization

我需要规范化数组,我找到最大值,可以是任何数字。我必须使用cout输出这个数字并将其表示为' x'多少次。问题是我最多只能容纳60 x。如果我的最大值是500,我需要将其显示为60' x'并将我的整个数组规范化为。我写的代码如下。

void RollDice() {  
int DieFace[6];
int Rolls = 0;
int Seed = 0;
int Random = 0; 
int i = 0; 
char X = 'x';

DieFace[0] = 0;
DieFace[1] = 0;
DieFace[2] = 0;
DieFace[3] = 0;
DieFace[4] = 0;
DieFace[5] = 0; 


cout << "Enter number of times dice will be rolled. "; //output to user
cin >> Rolls; //get rolls
cout << endl;


cout << "Enter desired seed number. "; //output to user
cin >> Seed; //get seed
cout << endl;
srand(Seed);


for (int i = 0; i < Rolls; ++i) { //loop for RNG
Random = 1 + rand() % 6;

// boolean to get Face
if (Random == 1)
    DieFace[0] = DieFace[0] + 1;
else if (Random == 2)
    DieFace[1] = DieFace[1] + 1;
else if (Random == 3)
    DieFace[2] = DieFace[2] + 1;
else if (Random == 4)
    DieFace[3] = DieFace[3] + 1;
else if (Random == 5)
    DieFace[4] = DieFace[4] + 1;
else if (Random == 6)
    DieFace[5] = DieFace[5] + 1;
} 

for (i = 0; i < 6; i++) {
cout << i + 1 << " Was Rolled: " << DieFace[i] << " Times." << endl;
}
cout << endl;

int Max = std::max({DieFace[0], DieFace[1], DieFace[2], DieFace[3], DieFace[4], DieFace[5] });   // find max value 

2 个答案:

答案 0 :(得分:1)

获得最高数量的DieFace,如果它高于你的最大值,你必须缩小它们(例如这样):

    int Max=0;
    for (int i = 0; i < 6; i++) {
        if (DieFace[i]>Max) Max = DieFace[i];
    }
    for ( int i=0;i<6;i++) {
        cout << i << ":" ;
        int numHashes = DieFace[i];
        if (Max > 60) {
            numHashes = DieFace[i]*60/Max;
        }
        for (int j=0;j<numHashes;j++)
            cout << "#";
        cout << endl;
    }

答案 1 :(得分:0)

假设你的Max是500.如果你乘以60然后除以500,结果就是60.如果你有另一个值是max(250)的一半,乘以60得到15000然后除以500得 30

因此,简单的解决方案是:将所有结果乘以所需最大值,然后除以实际最大值。

即使评论声称如此,您也不需要double500*60无法溢出。但是,使用long可能是明智之举,因为使用int会将其切割得相当接近。 600*60可能会溢出int(&gt; 32767),但long会溢出到20亿。