C# 什么是;使用未分配的局部变量;什么意思?
我一直收到这个错误的年费,月费,和滞纳金C# 什么是;使用未分配的局部变量;什么意思?,c#,unassigned-variable,C#,Unassigned Variable,我一直收到这个错误的年费,月费,和滞纳金 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;
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;
}
if (creditPlan == "2")
{
annualRate = 0.20; //20%
if (status == "y")
{
late = true;
}
else if (status == "n")
{
late = false;
}
if (late == true)
{
lateFee = 35.00;
}
if (balance > 100)
{
monthlyCharge = balance * (annualRate * (1 / 12));
}
else
{
monthlyCharge = 0;
}
return;
}
if (creditPlan == "3")
{
annualRate = 0.15; //15%
lateFee = 0.00;
if (balance > 500)
{
monthlyCharge = (balance - 500) * (annualRate * (1 / 12));
}
else
{
monthlyCharge = 0;
}
return;
}
netBalance = balance - (lateFee + monthlyCharge);
Console.WriteLine("Name: \t\t\t {0} {1}", firstName, lastName);
Console.WriteLine("Account Number: \t{0}", accNumber);
Console.WriteLine("Credit Plane: \t\t{0}",creditPlan);
Console.WriteLine("Account Late: \t\t{0}", late);
Console.WriteLine("Balance: \t\t{0}", balance);
Console.WriteLine("Late Fee: \t\t{0}", lateFee);
Console.WriteLine("Interest Charge: \t{0}", monthlyCharge);
Console.WriteLine("Net Balance: \t\t{0}",netBalance);
Console.WriteLine("Annual Rate: \t\t{0}", annualRate);
Console.ReadKey();
}
}
}
因为如果if语句的计算结果都不是true,那么局部变量将被取消赋值。在那里抛出一个else语句,并为这些变量分配一些值,以防if语句的计算结果不为true。如果这不能使错误消失,请发回这里
另一个选项是在代码开头声明变量时,将变量初始化为某个默认值。您的赋值都嵌套在条件if块中,这意味着它们可能永远不会被赋值
在类的顶部,将它们初始化为0或其他值将声明更改为:
double lateFee = 0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
导致此错误的原因是,代码中至少有一条路径没有设置这些变量。编译器说,如果无法识别CreditPlan,annualRate将没有值 创建局部变量(年费、月费和滞纳金)时,为其指定默认值(0)
此外,如果信用计划未知,则应显示错误。编译器不够聪明,无法知道至少会执行一个
if
块。因此,它没有看到像annualRate
这样的变量将被分配到任何情况下。以下是如何让编译器理解:
if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}
编译器知道,对于if/else块,其中一个块保证被执行,因此,如果在所有块中分配变量,它不会给出编译器错误
顺便说一句,您也可以使用
开关语句而不是if
s,以使代码更干净。并非所有代码路径都为延迟费设置了值。您可能希望在顶部为其设置一个默认值。您不会在if语句之外赋值。。。正如@iomaxx所指出的,信用可能不是0、1、2或3
尝试将单独的if语句更改为单个if/else if/else if/else。或者在顶部指定默认值。为它们指定默认值:
double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
基本上,所有可能的路径都不会初始化这些变量。如果您像这样声明变量“annualRate”
班级计划
{
试试看。在代码中有许多未初始化变量的路径,这就是编译器抱怨的原因
具体而言,您没有验证creditPlan
的用户输入-如果用户输入的值不是“0”、“1”、“2”或“3”
,则不会执行所指示的分支(并且creditPlan
不会根据用户提示默认为零)
正如其他人所提到的,编译器错误可以通过在检查分支之前对所有派生变量进行默认初始化,或者确保至少执行一个分支(即分支的互斥性,使用fall-throughelse
语句)来避免
不过,我想指出其他可能的改善:
- 验证用户输入,然后再信任它在代码中使用
- 将参数作为一个整体建模-每个计划都有几个属性和计算
- 对数据使用更合适的类型。例如,
CreditPlan
似乎有一个有限域,更适合于枚举
或字典
,而不是字符串
。财务数据和百分比应始终建模为十进制
,而不是双精度
,以避免四舍五入问题“tus”似乎是一个布尔值
- 停止重复代码。计算,
monthlyCharge=balance*annualRate*(1/12))
对于多个分支机构是通用的。出于维护原因,请勿重复此代码
- 可能更高级,但请注意,函数现在是C#的一等公民,因此您可以将函数或lambda指定为属性、字段或参数
e、 g.以下是您的模型的替代表示:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
//将所有信贷计划参数保存在一个模型中
公共类信贷计划
{
公共函数月收费{get;set;}
公共十进制年率{get;set;}
公共函数LateFee{get;set;}
}
//停止重复计算
静态私人十进制标准月收费(十进制余额、十进制年费率)
{
收益余额*年利率/12;
}
公共静态字典CreditPlans=新字典
{
{0,新计划
{
年利率=0.35M,
滞纳金==>0.0M,
月收费=标准月收费
}
},
{1,新的信贷计划
{
年利率=0.3000万,
迟到费=迟到=>迟到?0:25.0M,
月收费=标准月收费
}
},
{2,新信贷计划
{
年利率=.2000万,
迟到费=迟到=>迟到?0:35.0M,
月费用=(余额,年利率)=>余额>100
?余额*年利率/12
: 0
}
},
{3,新的信贷计划
{
年利率=0.15米,
滞纳金==>0.0M,
月费用=(余额,年利率)=>余额>500
?(余额-500)*年利率/12
: 0
}
}
};
使用关键字“default”
我不建议将if else
语句替换为两个if
。这不是最好的方法。您是否考虑过如果更改creditPlan的值会发生什么情况
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
string myString = default;
double myDouble = default;
if(!String.IsNullOrEmpty(myString))
myDouble = 1.5;
return myDouble;