English 中文(简体)
计算一个值并四舍五入到最接近的整数
原标题:Calculating a value and rounding to nearest whole number

我正在计算下面的一个数字。当它应该是83.12454时,我一直得到0。

我想我想要一个Double变量类型。下面我做错了什么?一旦我得到值,我就需要修剪小数。

Ratings GetNoVotes = new Ratings();
int DATotalYesVotes = GetNoVotes.GetTotalNOVotes(1, yesPictureId); //80
int DaTNoVotes = GetNoVotes.GetTotalNOVotes(2, yesPictureId);      //15
int DaTotalVotes = DATotalYesVotes + DaTNoVotes;                   //95

double Percentage = (DATotalYesVotes / DaTotalVotes)*100;          //84.2105
// Math.Round(Percentage);
TotalyesVotes.Text = Percentage.ToString();
问题回答

问题是DATotalYesVotes是一个小于DaTotalVotes的整数。因为/的意思是整数除法,所以它在乘以100之前先四舍五入。以下是两种方法:

(1) 先乘以100(仍然有一些舍入误差,但不多)

double Percentage = (DATotalYesVotes * 100 / DaTotalVotes); 

(2) 先选替身

double Percentage = ((double)DATotalYesVotes / (double)DATotalVotes)*100;

在划分之前,您需要将DATotalYesVotes和DaTotalVotes转换为两倍:

double Percentage = ((double)DATotalYesVotes / (double)DaTotalVotes)*100.0; 

换句话说,2个int的除法将产生第三个(并被截断)int。

整数除法得到一个零的整数结果,然后将其乘以100。尝试对其中一个数字进行双精度铸造。

double Percentage = ((double)DATotalYesVotes / DaTotalVotes)*100;     




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签