我将未分配的变量用于局部变量'a'
namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
float Salary, a;
Salary= 300;
if (Salary <= 100)
a = Salary * 0; // a = amount paid
Console.WriteLine("He Pays " + a);
if (Salary <= 200)
a = Salary * 5 / 100;
Console.WriteLine("He Pays " + a);
if (Salary <= 500)
a = Salary * 10 / 100;
Console.WriteLine("He Pays " + a);
if (Salary > 500)
a= Salary*15/100;
Console.WriteLine("He Pays " + a);
Console.In.ReadLine();
}
}
}
答案 0 :(得分:2)
使用当前语法,您将根据salary的值覆盖您的变量几次。你确定这是你想要的吗?如果没有,请确保在else子句中执行替代计算:
namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
float Salary = 300;
float a = 0;
if (Salary <= 100)
{
a = Salary * 0; // a = amount paid
}
else if (Salary <= 200)
{
a = Salary * 5 / 100;
}
else if (Salary <= 500)
{
a = Salary * 10 / 100;
}
else
{
a = Salary*15/100;
}
Console.WriteLine("He Pays " + a);
Console.In.ReadLine();
}
}
}
答案 1 :(得分:-1)
在使用之前,您需要指定a
变量。改变这一行
float Salary, a;
到这个
float Salary, a = 0;
以下是完整的修改代码
namespace ConsoleApplication36
{
class Program
{
public static void Main()
{
float Salary, a = 0;
Salary= 300;
if (Salary <= 100)
a = Salary * 0; // a = amount paid
Console.WriteLine("He Pays " + a);
if (Salary <= 200)
a = Salary * 5 / 100;
Console.WriteLine("He Pays " + a);
if (Salary <= 500)
a = Salary * 10 / 100;
Console.WriteLine("He Pays " + a);
if (Salary > 500)
a = Salary*15/100;
Console.WriteLine("He Pays " + a);
Console.In.ReadLine();
}
}
}
答案 2 :(得分:-1)
设置等于0的初始值
namespace ConsoleApplication36
{
class Program {
static void Main(string[] args) {
float Salary, a = 0; Salary= 300; if (Salary <= 100)
a = Salary * 0; // a = amount paid
Console.WriteLine("He Pays " + a);
if (Salary <= 200)
a = Salary * 5 / 100;
Console.WriteLine("He Pays " + a);
if (Salary <= 500)
a = Salary * 10 / 100;
Console.WriteLine("He Pays " + a);
if (Salary > 500)
a= Salary*15/100;
Console.WriteLine("He Pays " + a);
Console.In.ReadLine();
}
}
}
答案 3 :(得分:-1)
最好单独声明它们,因为你是C#
的新手浮动薪水; float a = 0;
错误是因为CLR足够聪明,可以在到达特定的局部变量使用之前检查代码所采用的路径,如果你可以在没有分配值的情况下到达那里就会抱怨。