Help with basic division in code?

Hey everyone! I'm taking a programming class in college, and it's been going really well so far. We do 2 labs a week, and each lab has us fix/write 3-5 programs. I'm on the 13th lab at the moment, and I can't seem to figure out why it's outputting 0. This lab is introducing us to using int when declaring variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// File: Lab13P1.cpp
// Created by Jason
// This program calculates BMI

#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
	int height = 0;
	int weight = 0;
	double bmi = 0.0;
	
	cout<< "Enter your height in inches: ";
	cin >> height;
	cout << "Enter your weight in pounds: ";
	cin >> weight;	

        bmi = (weight / (height * height) * 703);
	
	cout << "BMI: " << bmi << endl;

system("pause");
return 0;
}


Can anyone clue me in to the error?
Last edited on
Well, apparently using int to declare those variables wasn't the right thing to do. I switched them to double and it works now.

When are you supposed to use int to declare a variable?
Use int when you dont want fractions or decimal points.

e.g
1
2
int a = 4.2
cout<<a<<;   //will truncate the fractional part 


4
1
2
3
double pi = 22/7;
int x = pi;
cout<<x<<" "<<pi;


3   3.1415...
1
2
3
4
double a = 5;
int b = 2;
double c = 2;
cout<<a/b<<"  "<<a/c<<;  // double/int  = int 


2   2.5
Alright. Do you know why it would output 0 when int was being used to declare some variables? For example, I would put 66 for the height and 155 for the weight, and it'd give me 0.
hi,

Because of the nature of integer division : 155/ (66 * 66) is less than 1 so it returns 0.

Also be careful of integer overflow that can sometimes be a problem, or at least something that should be checked for a robust application. Check out the limits header if interested.

Cheers
Last edited on
Topic archived. No new replies allowed.