“使用未分配的局部变量”是什么意思?我的年率、月费和迟交都会出现这个错误。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贡献1821条经验 获得超6个赞
编译器不够聪明,不知道至少有一个if块将被执行。因此,它看不到这样的变量annualRate无论如何都会被分配。下面是如何让编译器理解的方法:
if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}
编译器知道,如果使用if/etc块,将保证执行其中一个块,因此,如果要在所有块中分配变量,则不会给编译器带来错误。
顺便说一句,您也可以使用switch语句而不是if也许是为了让你的代码更简洁。
汪汪一只猫
TA贡献1898条经验 获得超8个赞
double lateFee = 0.0;double monthlyCharge = 0.0;double annualRate = 0.0;
子衿沉夜
TA贡献1828条经验 获得超3个赞
- 3 回答
- 0 关注
- 704 浏览
添加回答
举报
0/150
提交
取消