“使用未分配的局部變量”是什么意思?我的年率、月費和遲交都會出現這個錯誤。using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Lab_5___Danny_Curro{
class Program
{
static void Main(string[] args)
{
string firstName;
string lastName;
int accNumber;
string creditPlan;
double balance;
string status;
Boolean late = false;
double lateFee;
double monthlyCharge;
double annualRate;
double netBalance;
Console.Write("Enter First Name: ");
firstName = Console.ReadLine();
Console.Write("Enter Last Name: ");
lastName = Console.ReadLine();
Console.Write("Enter Account Number: ");
accNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Credit Card Plan Number[Blank Will Enter Plan 0]: ");
creditPlan = Console.ReadLine();
Console.Write("Enter Balance: ");
balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Is This Account Late?: ");
status = Console.ReadLine().Trim().ToLower();
if (creditPlan == "0")
{
annualRate = 0.35; //35%
lateFee = 0.0;
monthlyCharge = balance * (annualRate * (1 / 12));
return;
}
if (creditPlan == "1")
{
annualRate = 0.30; //30%
if (status == "y")
{
late = true;
}
else if (status == "n")
{
late = false;
}
if (late == true)
{
lateFee = 25.00;
}
monthlyCharge = balance * (annualRate * (1 / 12));
return;
}
}
}}
3 回答

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
編譯器不夠聰明,不知道至少有一個if塊將被執行。因此,它看不到這樣的變量annualRate無論如何都會被分配。下面是如何讓編譯器理解的方法:
if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}
編譯器知道,如果使用if/etc塊,將保證執行其中一個塊,因此,如果要在所有塊中分配變量,則不會給編譯器帶來錯誤。
順便說一句,您也可以使用switch語句而不是if也許是為了讓你的代碼更簡潔。

當年話下
TA貢獻1890條經驗 獲得超9個贊
double lateFee = 0.0;double monthlyCharge = 0.0;double annualRate = 0.0;

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
- 3 回答
- 0 關注
- 326 瀏覽
添加回答
舉報
0/150
提交
取消