使用Sentinel值(C#)循环

本文关键字:循环 Sentinel 使用 | 更新日期: 2023-09-27 18:21:32

我确信这很简单,但我不知道我做错了什么。我试图输入300到850的有效信用评分,其中-99是一个前哨值,并以此为基础计算平均值。我可能错过了一些非常简单的东西(很可能)。。。请帮忙!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditScores
{
class Program
{
    static void Main(string[] args)
    {
      int creditScore;
        int totalScore = 0;
        int count = 0;
        int average;
        string user;
        Console.WriteLine("Enter credit score; press -99 to exit");
        user = Console.ReadLine();
        creditScore = Convert.ToInt32(user);
        count = ++count;
        totalScore += creditScore;
        while (creditScore != -99)
        {
            Console.WriteLine("Enter credit score; press -99 to exit");
            user = Console.ReadLine();
            creditScore = Convert.ToInt32(user);
            count = ++count;
            totalScore += creditScore;
            while (creditScore < 300 || creditScore > 850)
            {
                Console.WriteLine("Invalid score; please enter a valid credit score");
                user = Console.ReadLine();
                creditScore = Convert.ToInt32(user);
                count = ++count;
                totalScore += creditScore;
            }
        }
                average = totalScore / count;
                Console.WriteLine("The average of all {0} scores is {1}", count, average);             
        }
    }
}

使用Sentinel值(C#)循环

由于您澄清了只有当-99不是用户输入的第一个数字时才会发生这种情况,我只想缩小导致问题的while循环的范围。

当用户输入-99时,creditScore小于300,因此会打印"无效分数"消息。

执行过程中(注意我添加的注释)。

while (creditScore != -99)
{
    Console.WriteLine("Enter credit score; press -99 to exit");
    user = Console.ReadLine(); //User enteres '-99' here
    creditScore = Convert.ToInt32(user); //creditScore is evaluated to -99
    count = ++count;
    totalScore += creditScore;
    //This is what's causing the problem. 
    //This is now: while (-99 < 300 || -99 > 850)
    //Notice that -99 < 300 is true, and therefore the while loop is executed
    while (creditScore < 300 || creditScore > 850)
    {
        //Execution reaches here when creditScore = -99
        Console.WriteLine("Invalid score; please enter a valid credit score");
        user = Console.ReadLine();
        creditScore = Convert.ToInt32(user);
        count = ++count;
        totalScore += creditScore;
    }
}

要解决这个问题,你需要添加一个单独的条件来检查creditScore是否为-99并处理它。

这似乎是一个家庭作业问题,所以我将把它作为一个例外留给你,但如果不告诉我,我可以在解决方案中编辑:)