【发布时间】:2019-01-11 07:14:16
【问题描述】:
我无法在 c# 中从我的字典中减去项目
这是代码,我正在尝试获取 fruits.Count 作为 int。
public class test
{
public static void Main()
{
int totalStock = 10;`
Dictionary<string, int> fruits = new Dictionary<string, int>();
fruits.Add("Apples", 3);
fruits.Add("pears", 4);
int fruitsCount = fruits["Apples" + "pears"];
if(fruitsCount > totalStock){
Console.WriteLine("You have too many fruits! Please get rid of " + fruitsCount - totalStock + " fruits");
}
else if(fruitsCount = totalStock){
Console.WriteLine("You have just the right amount of fruits!");
}
else{
Console.WriteLine("You can fit " + totalStock - fruitsCount + " fruits");
}
}
}
但我遇到了错误:
退出状态 1 main.cs(14,21): error CS0019: Operator `-' cannot be 应用于'string'和'int'类型的操作数
main.cs(16,10): 错误 CS0029:无法将类型“int”隐式转换为“bool”
main.cs(20,21): 错误 CS0019:运算符“-”不能应用于类型的操作数 “字符串”和“整数”
【问题讨论】:
-
elseif 似乎也有问题 - 您尝试 assing
fruitStock = totalStock而不是比较它们。 -
字典由键访问,在您的情况下是
string类型。 Int 这一行int fruitsCount = fruits["Apples" + "pears"]您正在连接两个字符串,因此您正在尝试访问名为fruits["Applespears"]的产品,该产品不在字典中。改成int fruitsCount = fruits["Apples"] + fruits["pears"] -
c#中的相等比较器是
==而不是= -
“
Operator '-' cannot be applied to operands of type 'string' and 'int'”是因为"... rid of " + fruitsCount - totalStock + " fruits"你必须手动进行一些类型转换或使用新变量,我会int excessOfFruit = fruitsCount - totalStock并在 Console.WriteLine 指令中使用该变量。
标签: c#