【问题标题】:Adding value to int variable each run of the loop每次循环运行都向 int 变量添加值
【发布时间】:2020-10-17 08:47:13
【问题描述】:

对不起,如果这是一个重复的问题或听起来很愚蠢,但我真的是 c# 新手,浏览了整个论坛,找不到任何我能真正理解的东西。

所以我正在尝试编写一个简单的程序,让用户尝试猜测 1 到 25 之间的数字。除了每次运行循环而不是更新循环最后一次运行的分数(例如 0)之外,一切正常+1=1, 1+1=2, 2+1=3,每次加1到0。这是我的代码。我该如何解决?谢谢!

int score = 0;
int add = 1;

while (add == 1)
{
    Console.WriteLine("Guess A Number Between 1 and 25");
    string input = Console.ReadLine();

    if (input == "18")
    {
        Console.WriteLine("You Did It!");
        Console.WriteLine("Not Bad! Your Score was " + score + add);
        break;
    }
    else
    {
        Console.WriteLine("Try Again. Score: " + score + add);
    }
}

【问题讨论】:

    标签: c# if-statement while-loop int


    【解决方案1】:

    您实际上需要将add 添加到score。试试这样的:

    int score = 0;
    int add = 1;
    
    while (add == 1)
    {
        Console.WriteLine("Guess A Number Between 1 and 25");
        string input = Console.ReadLine();
    
        score += add; // add `add` to `score`. This is the same as `score = score + add;`
    
        if (input == "18")
        {
            Console.WriteLine("You Did It!");
            Console.WriteLine("Not Bad! Your Score was " + score);
            break;
        }
        else
        {
            Console.WriteLine("Try Again. Score: " + score);
        }
    }
    

    【讨论】:

    • source += add 与 source = source + add 是一回事,如果您是 C# 新手,可能会感到困惑
    猜你喜欢
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多