简单计算误差 [英] Simple Calculation Error
本文介绍了简单计算误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我遇到问题的简短代码段:
Here is a short code snippet that I am having trouble with:
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
int k = DepthOfDischarge.SelectedIndex;
double DoD = DoD = 10 / (k + 1);
//MessageBox.Show(DoD.ToString());
return (DoD);
}
组合框有10个项目:10%,20%,...,90%,100%.
现在,如果我选择说组合框中的第三项(30%),则DoD变量将存储3而不是3.33333333 ...
如果我在组合框中选择说第7项(占70%),则mod将读取1,而不是1.42857 ...
小数点似乎被截断了.为什么会在双精度"或十进制"数据类型中发生这种情况?
我缺少重要的东西吗?
The combobox has 10 items: 10%, 20%, ... , 90%, 100%.
Now if I select say the third item (30%) in the combobox, the DoD variable stores 3 and not 3.33333333...
If I select say the 7th item, (70%) in the combobox, then the DoD reads 1 and not 1.42857...
The decimal seems to be truncated. Why is this happening in a ''double'' or ''decimal'' data type?
Am I missing something important?
推荐答案
使用浮点值而不是整数:
Use floating-point values instead of integers:
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
double k = Convert.ToDouble(DepthOfDischarge.SelectedIndex);
double DoD = 10.0 / (k + 1.0);
//MessageBox.Show(DoD.ToString());
return (DoD);
}
尝试使用double DoD = DoD = 10.0 / (k + 1.0);
private double DetermineBatteryDepthOfDischarge(ComboBox DepthOfDischarge)
{
Double k = cdbl(DepthOfDischarge.SelectedIndex);
Double DoD = 10.0 / (k + 1.0);
//MessageBox.Show(DoD.ToString());
return (DoD);
}
这篇关于简单计算误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文