我确信这很简单,但我无法弄清楚我做错了什么。我试图输入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);
}
}
}
答案 0 :(得分:0)
由于您明确说明只有在-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并处理该问题。
这似乎可能是一个家庭作业问题,所以我会把它留给你作为一个例外,但如果不让我知道,我可以在解决方案中编辑:)