【问题标题】:How to multiply int Random by int in C# [duplicate]如何在 C# 中将 int Random 乘以 int [重复]
【发布时间】:2021-03-02 21:35:42
【问题描述】:

我遇到了一个小问题 - 我正在尝试在控制台应用中将 random 乘以 int。我有一个错误:

运算符“*”不能应用于“随机”和“整数”类型的操作数

我已经尝试过:rndAttackPoints = attackPoints 然后

这个int damagePoints = (rndAttackPoints * strenghtPoints1) - defencePoints1;进入

这个int damagePoints = (attackPoints * strenghtPoints1) - defencePoints1; 但这不起作用。

所以我问你,你知道如何在 C# 中将 Random 乘以 int 吗?

            //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;

【问题讨论】:

  • 提示:您通过rndAttackPoints.Next(5, 10) 获得随机值,而不是通过将rndAttackPoints 转换为int
  • new Random() 是可以生成随机事物的东西。 rndAttackPoints.Next(5, 10) 是获取您正在寻找的随机值的方法。存储结果。

标签: c# random console console-application multiplication


【解决方案1】:

将随机值保存在单独的变量中,并按如下方式处理:

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

int damagePoints = (rnd * strenghtPoints1) - defencePoints1;

【讨论】:

  • 谢谢,这比我想象的要容易:)
猜你喜欢
  • 2015-04-12
  • 2014-08-29
  • 2012-08-04
  • 2017-07-17
  • 1970-01-01
  • 2012-12-12
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多