【问题标题】:Looping with Sentinel Values (C#)使用 Sentinel 值循环 (C#)
【发布时间】:2015-11-12 03:30:18
【问题描述】:

我确信这很简单,但我不知道我做错了什么。我正在尝试输入从 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);             

        }

    }
}

【问题讨论】:

  • 如果我输入 -99,它总是返回“无效分数;请输入有效的信用分数”并且从不显示平均值。
  • 即使是您输入的第一个数字也会发生这种情况吗?
  • 如果是我输入的第一个数字,它会说“所有 1 分的平均值是 -99”。
  • 尝试运行代码step by step 看看哪里出错了。

标签: c# while-loop average sentinel


【解决方案1】:

既然您澄清了这种情况只有在 -99 不是用户输入的第一个数字时才会发生,所以我将缩小导致问题的 while 循环。

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

随着执行(注意我添加的 cmets)。

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 并进行处理。

这似乎是一个家庭作业问题,所以我将把它作为练习留给你,但如果不让我知道,我会在解决方案中进行编辑:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2016-06-12
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多