Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a better way to write these If-Statements?

I’m building a Random Character Generator in C++, and I have around 12 large blocks of if statements, like this:

int wisdom = rand() % 18;

cout << "\n";

if (wisdom == 0 || wisdom == 1) {

    cout << "Wisdom Score: 1\n";
    cout << "Modifier: -5\n";

} else if (wisdom == 2 || wisdom == 3) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: -4\n";

} else if (wisdom == 4 || wisdom == 5) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: -3\n";

} else if (wisdom == 6 || wisdom == 7) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: -2\n";

} else if (wisdom == 8 || wisdom == 9) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: -1\n";

} else if (wisdom == 10 || wisdom == 11) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: +0\n";

} else if (wisdom == 12 || wisdom == 13) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: +1\n";

} else if (wisdom == 14 || wisdom == 15) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: +2\n";

} else if (wisdom == 16 || wisdom == 17) {

    cout << "Wisdom Score: " << wisdom << "\n";
    cout << "Modifier: +3\n";

} else {

    cout << "Wisdom Score: 18\n";
    cout << "Modifier: +4\n"; 

}

I’m wondering, is there a better way to write this? Perhaps some type of function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need any conditionals. Also, don’t use rand() %.

std::mt19937 mt(42); // seed
auto const wisdom = std::uniform_int_distribution<int>(0,18)(mt);
auto const score = wisdom + !wisdom;
auto const mod = wisdom / 2 - 5;

std::cout << "Wisdom Score: " << score << "\n";
std::cout << "Modifier: " << mod << "\n";

This assumes it is intentional that you have a double chance of wisdom score 1 proccing compared to other scores. If not change the lower bound in the std::uniform_int_distribution construction from 1 to 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading