小数、整数、转换...天哪!
我正在阅读“Head First C#”一书,在其中一章中,我创建了一个程序并使用声明为整数和小数的变量。 Visual Studio 有几次因为混合和匹配这两者而对我发脾气。 例如:
dinnerParty.NumberOfPeople = (int) numericUpDown1.Value;
NumberOfPeople 被声明为 int,显然数字 updowns 是小数。
此外,当将一些数字相加时,本书会在它们后面添加一个 M。 例如:
public void SetHealthyOption(bool healthy)
{
if (healthy)
{
CostOfBeveragesPerPerson = 5.00M;
}
else
{
CostOfBeveragesPerPerson = 20.00M;
}
}
CostOfBeveragesPerPerson 被声明为小数。
所以我有两个具体问题:
1)你怎么知道什么时候需要投射某些东西? 我确信选角有很多内容......任何人都可以提供一些好的链接来了解选角吗?
2)数字后面的M有什么作用?
编辑
所以 M 表示该数字是十进制而不是双精度数。 为什么不直接将数字转换为小数,例如:(十进制)50.00? 这个“功能”叫什么? 如果我想看看有哪些“字母”可用,我会用谷歌搜索什么?
I'm going through the "Head First C#" book and in one of the chapters I created a program and uses variables declared as ints and decimals. Visual Studio got cranky with me a couple of times about mixing and matching the two. For example:
dinnerParty.NumberOfPeople = (int) numericUpDown1.Value;
NumberOfPeople is declared as an int and apparently numeric updowns are decimals.
Also, the book puts an M after some numbers when adding them together. For example:
public void SetHealthyOption(bool healthy)
{
if (healthy)
{
CostOfBeveragesPerPerson = 5.00M;
}
else
{
CostOfBeveragesPerPerson = 20.00M;
}
}
CostOfBeveragesPerPerson is declared as a decimal.
So I have two specific questions:
1) How can you know when you need to cast something? I'm sure there is quite a bit to casting... can anyone provide some good links to learn about casting?
2) What does the M after the numbers do?
EDIT
So the M denotes that the number is a decimal and not a double. Why not just cast the number as a decimal like: (decimal) 50.00? And what is that "function" called? If I wanted to see what "letters" were available what would I google?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有很多页面解释 C# 数字文字。 末尾的字母不是强制转换或任何类型的函数。 它的语法显示您正在编写的内容代表特定类型的值。 因此,写(十进制)5.0 使用强制转换,但写 5.0m 则不使用强制转换。
There's a lot of pages that explain C# numeric literals. The letter at the end is not a cast or any kind of function. It is syntax showing that what you are writing represents a value of a particular type. So writing (decimal) 5.0 uses a cast, but writing 5.0m does not.
十进制
,否则它将假定它是double
decimal
, otherwise it will assume it to be adouble