2015-05-09 35 views
0

我想寫一個模擬汽車競賽比賽的程序,用戶在比賽中插入汽車的數量和每輛車的時間。該計劃將以最快的時間打印車輛,並以最快的時間打印車輛。我的編譯器總是說我沒有分配我的變量

所以我寫了這個代碼:

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(); 
     } 
    } 
} 

我得到這個錯誤:

Use of unassigned local variable 'second'

我不明白爲什麼我得到這個錯誤。

+0

請顯示完整的堆棧跟蹤 –

+0

它有助於顯示哪行代碼導致相對於帖子的錯誤。 – ChiefTwoPencils

+0

C#編譯器不允許您使用未分配的本地變量。你的「for」從來沒有用過?編譯器無法知道這一點。這並不聰明。 –

回答

1

您聲明變量:

int numc, first, second, time, i, temp; 

然後你可能指派方式:

for (i = 0; i < numc; i++) 
{ 
    // etc. 
    if(time<first) 
    { 
     temp=first; 
     first = time; 
     second = temp; 
    } 
    // etc. 
} 

(或者你可能不會,這取決於在運行時的狀況或numc在運行時的值)

然後你使用它:

Console.WriteLine("The time of the car who got second place is:" +second); 

如果if條件的計算結果爲false會發生什麼情況?或者如果for循環沒有迭代任何東西?然後在使用它之前,變量永遠不會被分配。這就是編譯器告訴你的。

如果您要始終使用該變量,那麼您需要確保始終爲其分配一些值。

0

這條線:

Console.WriteLine("The time of the car who got second place is:" +second); 

使用second變量這是未分配,當numc < 1time >= first

使用

int second = 0; 

初始化這個領域。

1

這裏的問題是,你的任務

如果 numc輸入小於一個
second = temp 

將不會執行。

由於編譯器不能保證它已被分配,它會給你警告。

在你的情況,你可以不喜歡分配

int second = 0; 

但你可能想改變Console.WriteLine有點過了,喜歡的東西:

if (numc > 0) 
{ 
    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); 
} 
else 
{ 
    Console.WriteLine("No cars were in the competition"); 
} 

Console.ReadLine(); 
2

你只是在內部分配second這個循環:

if(time<first) 
{ 
    temp=first; 
    first = time; 
    second = temp; 
} 

如果你做什麼沒有進入這個如果?

如果您想稍後使用它,則必須確保將其分配到任何地方。

相關問題