02 Jul, 2008, David Haley wrote in the 21st comment:
Votes: 0
I think that if you want it to be an int, in light of the inconsistency observed across machines, the safest is probably to cast it to an int in the argument list.
02 Jul, 2008, Guest wrote in the 22nd comment:
Votes: 0
Zeno said:
Going back to the original code that I said worked:
sprintf( buf, "Test: %d\n\r", get_curr_vig(ch)*((float)ch->pcdata->strform/100) );
send_to_char( buf, ch );

Prints:
Quote
Test: 300


So am I missing something here? That is returning a valid number. Is there a typo in the code that I'm not seeing and thus is different from the clean version we tried out?


This example is actually downcast internally to an int before being passed to the %d. Basically you have:

get_curr_vig(ch) and ((float)ch->pcdata->strform/100)

Order of operations. The division in parentheses is carried out first - and ch->pcdata->strform is temporarily cast to a float, then divided by 100.
This results in an integer for the next step, which is multiplied by get_cur_vig(ch). The final answer is already an integer before ever reaching ch_print.

Now, as far as autoconverting to an int, that seems to be undefined result behavior. Sort of like when you fclose() a file but forget to NULL the pointer. Remember the Redhat 6 days when this first started to be an issue? :)
02 Jul, 2008, Caius wrote in the 23rd comment:
Votes: 0
Samson said:
This example is actually downcast internally to an int before being passed to the %d. Basically you have:

get_curr_vig(ch) and ((float)ch->pcdata->strform/100)

Order of operations. The division in parentheses is carried out first - and ch->pcdata->strform is temporarily cast to a float, then divided by 100.
This results in an integer for the next step, which is multiplied by get_cur_vig(ch). The final answer is already an integer before ever reaching ch_print.


It's not at integer when it's passed as an argument to sprintf. The proof is as follows:
#include <iostream>
#include <cstdio>

int main()
{
printf( "Integer division: 7/4 is %1.2f\n", (float)(7/4) );
printf( "Floating division: 7./4. is %1.2f\n", 7./4. );
printf( "Mixed division1: 7./4 is %1.2f\n", 7./4 );
printf( "Mixed division2: 7/4. is %1.2f\n", 7/4. );
printf( "Mixed division (convert to int): 7./4 is %d (undefined)\n", 7./4 );
printf( "Zeno example1: 3 * (7./4) is %1.2f\n", 3 * (7./4) );
printf( "Zeno example2: 3 * (7./4) is %d\n", 3 * (7./4) );
std::cout << "cout result: 3 * (7./4) is "
<< 3 * (7./4) << '\n';
}


Output:
Quote
Integer division: 7/4 is 1.00
Floating division: 7./4. is 1.75
Mixed division1: 7./4 is 1.75
Mixed division2: 7/4. is 1.75
Mixed division (convert to int): 7./4 is 0 (undefined)
Zeno example1: 3 * (7./4) is 5.25
Zeno example2: 3 * (7./4) is 0
cout result: 3 * (7./4) is 5.25
20.0/23