【发布时间】:2015-05-09 18:17:44
【问题描述】:
我正在尝试编写一个模拟赛车比赛的程序,用户插入比赛中的汽车数量和每辆车的时间。该程序将打印时间最快的汽车和第二快的汽车。
所以我写了这段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int numc, first, second, time, i, temp;
Console.WriteLine("Please insert the number of cars in the competition");
numc = int.Parse(Console.ReadLine());
Console.WriteLine("Please insert the time it took the car to finish the race");
time = int.Parse(Console.ReadLine());
first = time;
for (i = 0; i < numc; i++)
{
Console.WriteLine("Please insert the time it took the car to finish the race");
time = int.Parse(Console.ReadLine());
if(time<first)
{
temp=first;
first = time;
second = temp;
}
}
Console.WriteLine("The time of the car who got first place is:" +first);
Console.WriteLine("The time of the car who got second place is:" +second);
Console.ReadLine();
}
}
}
我收到此错误:
使用未赋值的局部变量'second'
我不明白为什么会出现这个错误。
【问题讨论】:
-
请显示您的完整堆栈跟踪
-
它有助于显示与此处的帖子相关的哪一行代码导致错误。
-
C# 编译器不允许您使用未分配的局部变量。什么是你的
for从来不工作?编译器无法知道这一点。它没那么聪明。 -
@MoH。这也不例外。这是编译时出现的错误消息。