gpt4 book ai didi

c# - c# 中的减法?

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:28 24 4
gpt4 key购买 nike

我不能在 C# 中从我的字典中减去项目

这是代码,我正在尝试获取水果。将其计数为 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");
}

}
}

但是我收到错误:

exit status 1 main.cs(14,21): error CS0019: Operator `-' cannot beapplied to operands of type 'string' and 'int'

main.cs(16,10): errorCS0029: Cannot implicitly convert type 'int' to 'bool'

main.cs(20,21):error CS0019: Operator '-' cannot be applied to operands of type'string' and 'int'

最佳答案

没有 "Apples"+ "pears"== "Applespears" 水果,这就是原因

fruits["Apples" + "pears"];

错了。把它写成 fruits["Apples"] + fruits["pears"];:

public static void Main() {
int totalStock = 10;

Dictionary<string, int> fruits = new Dictionary<string, int>() {
{"Apples", 3},
{"pears", 4},
};

// Either Apples + pears
int fruitsCount = fruits["Apples"] + fruits["pears"];
// ... Or sum of all the fruits
// int fruitsCount = fruits.Values.Sum();

if (fruitsCount > totalStock){
Console.WriteLine($"You have too many fruits! Please get rid of {fruitsCount - totalStock} fruits");
}
else if(fruitsCount == totalStock) { // should be comparison "==" not assignement "="
Console.WriteLine("You have just the right amount of fruits!");
}
else {
Console.WriteLine($"You can fit {totalStock - fruitsCount} fruits");
}

注意string:我们不能减去string,只能减去整数;在你的情况下string interpolation是解决方案(我们在字符串中减去 整数):

  $"You have too many fruits! Please get rid of {fruitsCount - totalStock} fruits"

$"You can fit {totalStock - fruitsCount} fruits"

关于c# - c# 中的减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54141905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com