I am greatly liking WxWidgets, and started with C++ programming in it. My sample program converts Celsius into Fahrenheit from a text form. Here is my basic code:
//get "100" from textbox
wxString szCelsius = TextCtrl1->GetValue();
long lCelsius;
//attempt to cast into long
szCelsius.ToLong(&lCelsius, 10);
//formula that works in normal cases to get fahrenheit
long lFahrenheit = ((9.f/5.f) * lCelsius + 32);
//SOMEHOW this works:
//long lFahrenheit = ((9.f/5.f) * 100 + 32);
//display debug info, note it displays lCelsius as 100
wxString debuginfo;
debuginfo << _T("deg C: ") << lCelsius << _T("\n");
//displays incorrectly as 211
debuginfo << _T("deg F: ") << lFahrenheit << _T("\n");
//this displays开发者_Python百科 100
std::cout << lCelsius;
//this fails though
assert(lCelsius == 100);
Now with the debug info, lCelcius is 100 like expected but it returns fahrenheit as 211 instead of 212! The odd thing is that formula works fine in pure C, and when I replace lCelsius
with 100
, it works fine, even though my debug info clearly says it is 100.
Do you see any obvious problem or am I just not able to do such a simple thing? I am not sure quite what Wx is doing to make it one less than it should.
EDIT: including assert.h and running lCelsius == 100 fails in debugger, but std::cout lCelsius returns 100. There must be something up with Wx that is mangling the result but still is "100"..
The value 1.8 (which is 9/5) cannot be exactly represented as a binary floating point number - in binary, it is an recurring series of digits (1.1100110011001100110011001100...) - similar to the way 1/3 is recurring in decimal.
The closest representation as a single-precision floating point value is just under 1.8 - it's approximately 1.7999999523). When this number is multiplied by 100, it results in a value just under 180; and when 32 is then added, it results in a number just under 212.
Converting a floating point number to an integer truncates the decimal portion, so 211.999... becomes 211.
The reason it doesn't happen if you use a literal 100 in the source code, instead of a runtime-supplied value, is because the compiler simplified the expression (9.f/5.f) * 100
at compile time down to a plain 180.
If your compiler supports the C99 roundf()
function (declared in math.h
), you can use that to round to the nearest integer:
long lFahrenheit = roundf((9.f/5.f) * lCelsius + 32);
You could try debugging this at the assembly level, to see in more detail what is going on.
Also, just as a stylistic suggestion, the leading term could be written as (9.f / 5.f)
which gets rid of the casts and is easier to read.
I also question why you use long
for the temperature, to me it feels as if most temperatures (especially involving Fahrenheit) are in the range supported by plain int
.
精彩评论