基本数学C#不起作用 [英] Basic Maths C# Not Working

查看:75
本文介绍了基本数学C#不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这些都不能在C#中工作?

Why won't either of these work in C# ??

// Expected: 0.5, Output: 0

Console.WriteLine("Result #1: " + (50 / 100));

int iFifty = 50;
int iOneHundred = 100;
Console.WriteLine("Result #2: " + (iFifty / iOneHundred));

推荐答案

它是整数除法,您需要加倍:

it is an integer division, you need doubles:

Console.WriteLine("Result #1: " + (50 / 100d));

或者:

Console.WriteLine("Result #1: " + (50 / 100.0));

如果两个操作数均为integer,则执行整数除法,因此得到integer结果.如果使用'd'文字,则应明确指出该数字应视为并将其他操作数自动提升为double,然后执行双除,您将获得正确的结果.请参见

If both operands are integer, an integer division is performing therefore you get an integer result.If you use 'd' literal you explicitly state that number should be considered as double and other operand is promoted to double automatically, then a double division is performing and you get the correct result.See C# Specification Section 2.4.4 Literals for more info about literals and also you migh want take a look at Floating-Point Types in C#

这篇关于基本数学C#不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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