Search code examples
c#randomconsoleconsole-applicationmultiplication

How to multiply int Random by int in C#


I've got a little problem - I'm trying to multiply random by int in console app. And I've got an error:

Operator '*' cannot be applied to operands of Type 'Random' and 'int'

I've tride: rndAttackPoints = attackPoints and then

this int damagePoints = (rndAttackPoints * strenghtPoints1) - defencePoints1; into

this int damagePoints = (attackPoints * strenghtPoints1) - defencePoints1; but this didn't work.

So I'm asking you, do you know how to multiply Random by int in C#?

            //Elf
            int healthPoints1 = 100;
            int defencePoints1 = 3;
            int strenghtPoints1 = 2;

            // Goblin
            int healthPoints2 = 100;
            int defencePoints2 = 5;
            int strenghtPoints2 = 1;

            Random rndAttackPoints = new Random();            
            Console.WriteLine($"You've attacked: {rndAttackPoints.Next(5, 10)} HP");

            int damagePoints = (rndAttackPoints * strenghtPoints1) - defencePoints1;

Solution

  • Save the random value in a separate variable and work with that as follow:

    Random rndAttackPoints = new Random();
    int rnd = rndAttackPoints.Next(5, 10);
    Console.WriteLine($"You've attacked: {rnd} HP");
    
    int damagePoints = (rnd * strenghtPoints1) - defencePoints1;