使用/运算符的C#奇怪行为 [英] C# strange behavior with / operator

查看:90
本文介绍了使用/运算符的C#奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我为什么C#中的以下语句求值为int结果2而不是2.5

  float  f =  5  /  2 ; 
Console.WriteLine(f);



相同的代码在C语言中工作,输出2.0000而不是2.5000

 < span class =code-keyword> float  f = 5/2; 
printf( %f,f);



和C ++的工作原理与C#相同,并给出输出2

  float  f = 5 /  2 ; 
cout<< f;





我的尝试:



我试图在不同的论坛上对此进行调查。它非常简单的概念,所以我在这里发布它以了解关于此的专家意见。

解决方案

看看这个 [ ^ ]主题,它处理一个类似的问题。


这是因为你'指定两个整数(5和2),而不是浮点值。



将代码更改为(在C#中):

< pre lang =C#> float f = 5f / 2f;
Console.WriteLine(f);





在大多数语言中,如果没有指定小数点(5)而不是5.0)该值将被视为整数。整数除法永远不会返回浮点值,因此得到2而不是2.5。


在C#中,默认情况下,/运算符在System.Int32中返回结果。

 System。 Int32  answer =  5  /  2 ; 



如果你想要回答浮点数或双倍只做显式投票。

  decimal  answerInDeciaml =( decimal  5  /  2 ; 


Can anyone tell me why the following statement in C# evaluates to an int result 2 instead of 2.5

float f = 5 / 2;
Console.WriteLine(f);


Same code works in C Language and give the output 2.0000 rather than 2.5000

float f = 5/2;
printf("%f",f);


and C++ works same like to C# and gives the output 2

float f = 5/ 2;
cout<<f; 



What I have tried:

I've tried to investigate this on different forums . Its pretty simple concept so I've posted it here to know the expert opinion about this.

解决方案

Take a look at this[^] thread, it deals with a similar question.


It's because you're specifying two integers (5 and 2), not floating point values.

Change the code to (in C#):

float f = 5f / 2f;
Console.WriteLine(f);



In most languages, if you don't specify a decimal pointed value (5 instead of 5.0) the value will be treated as an integer. Integer division will never return a floating point value, so you get 2 instead of 2.5.


In C# by default the / operator returns the result in System.Int32.

System.Int32 answer = 5 / 2;


if you want answer in float or double just do explicit casting.

decimal answerInDeciaml = (decimal)5 / 2;


这篇关于使用/运算符的C#奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆