www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - a FOR loop and floating variables

reply "Carlos" <checoimg gmail.com> writes:
I have this code :

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}
  Which works. but if I change the "5.0" for "5" I get cero on the 
celsius side.

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5/9)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}

So why is this ?
May 02 2013
next sibling parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On 2013-05-02, 20:14, Carlos wrote:

 I have this code :

 import std.stdio;
 import std.c.stdlib;
 void main()
 {
 int fahr;
 write("F\tC\n");
 for (fahr = 0; fahr <= 300; fahr = fahr + 20)
 write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
 write("Done!\n");
 exit (0);
 }
   Which works. but if I change the "5.0" for "5" I get cero on the  
 celsius side.

 import std.stdio;
 import std.c.stdlib;
 void main()
 {
 int fahr;
 write("F\tC\n");
 for (fahr = 0; fahr <= 300; fahr = fahr + 20)
 write(fahr, "\t", (5/9)*(fahr-32), "\n");
 write("Done!\n");
 exit (0);
 }

 So why is this ?
Both 5 and 9 in the second example are integers (int). When you divide one int by another, the result is an int, and hence (5/9) is 0. -- Simen
May 02 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Simen Kjaeraas:

 Both 5 and 9 in the second example are integers (int). When you 
 divide
 one int by another, the result is an int, and hence (5/9) is 0.
Yes, smarter languages (like Pascal..., but also Python, Ada, etc) have two different division operators to avoid such silly C semantics, that sometimes causes bugs. Bye, bearophile
May 02 2013
prev sibling parent =?UTF-8?B?TWFydGluIERyYcWhYXI=?= <drasar ics.muni.cz> writes:
Dne 2.5.2013 20:14, Carlos napsal(a):
 I have this code :

 import std.stdio;
 import std.c.stdlib;
 void main()
 {
 int fahr;
 write("F\tC\n");
 for (fahr = 0; fahr <= 300; fahr = fahr + 20)
 write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
 write("Done!\n");
 exit (0);
 }
   Which works. but if I change the "5.0" for "5" I get cero on the
 celsius side.

 import std.stdio;
 import std.c.stdlib;
 void main()
 {
 int fahr;
 write("F\tC\n");
 for (fahr = 0; fahr <= 300; fahr = fahr + 20)
 write(fahr, "\t", (5/9)*(fahr-32), "\n");
 write("Done!\n");
 exit (0);
 }

 So why is this ?
Hi Carlos, the second code performs integral division which very much behave like floating-point division, but the fractional part is chopped off. 5/9 ~ 0.556 => 0 10/9 ~ 1.111 => 1 If you want precise (i.e. floating point) results, you have to have at least one float or double in your equation. This would work: write(fahr, "\t", (5.0/9)*(fahr-32), "\n"); Regards, Martin
May 02 2013