float f = 1 / 3

Jan 7, 2010 at 7:36pm
closed account (jLNv0pDG)
1
2
float f = 1 / 3;
cout << f;

0


How can I make f = .333?

I assume that 1/3 is being calculated/truncated as an int.

---

EDIT: How do you get output to line up with code on this board?
Last edited on Jan 7, 2010 at 7:37pm
Jan 7, 2010 at 7:37pm
Short answer: float f = 1.0 / 3.0;
Jan 8, 2010 at 7:34am
use: float f = (float)1/3;
Jan 8, 2010 at 1:51pm
EDIT: How do you get output to line up with code on this board?


You include the output in the code tag along with the code, separated by at least three dashes/minus signs "---" Any more than three will still work...

The following:
[code]
#include<iostream>

using namespace std;

int main(){
  cout << "Hello World!" << endl;
  return 0;
}

---
Hello World!

[/code]


produces:
1
2
3
4
5
6
7
8
9
#include<iostream>

using namespace std;

int main(){
  cout << "Hello World!" << endl;
  return 0;
}
Hello World!

Topic archived. No new replies allowed.