简体   繁体   English

如何从int取值? C#

[英]How to take away a value from an int? C#

The problem is on line 3, I need to take away a number between 1-3 and save the value so more can be taken away. 问题出在第3行上,我需要带走1-3之间的数字并保存值,以便可以带走更多的数字。

Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
int life = life - randomNumberhit;
Console.WriteLine(life);

Any ideas? 有任何想法吗? Am I doing it completely wrong? 我做错了吗?

You're declaring the variable life and assigning it a value of life - randomhit . 您要声明变量life并为其分配一个life - randomhit值。 How can you know the result of the calculation if life doesn't yet have a value? 如果life还没有价值,您如何知道计算结果?

Try something like this: 尝试这样的事情:

int life = 100;
...
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
life = life - randomNumberhit;
Console.WriteLine(life);

However, you may want to make life class variable instead. 但是,您可能要使life类变量可变。 Something like this would work: 这样的事情会起作用:

public class MyGuy
{

    public int Life { get; set; }

    public MyGuy()
    {
        this.Life = 100; // starting life
    }

    public void Hit()
    {
        Random randomhit = new Random();
        int randomNumberhit = randomhit.Next(1, 4);
        this.Life -= randomNumberhit;
        Console.WriteLine(this.Life);
    }
}

life need to be initalized to something 生活需要激发一些东西

int life = 100; //Or some other value
Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
life = life - randomNumberhit;
Console.WriteLine(life);

Also note that when life is reassigned ( life = life - randomNumberhit; ) the int is not needed. 还要注意,当重新分配life = life - randomNumberhit;时( life = life - randomNumberhit; ),不需要int。

You are doing life-randomNumberhit , but at that point your variable life does not exist yet. 您正在执行life-randomNumberhit ,但那时您的可变life尚不存在。 You should initialize your life variable to whatever value you want: 您应该将life变量初始化为所需的任何值:

Random randomhit = new Random();
int randomNumberhit = randomhit.Next(1, 4);
int life = 0; // for instance, 0
Console.WriteLine(life - randomNumberhit);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM