Code Help.

Started by
4 comments, last by Emotions06 17 years, 5 months ago
Okay so I am doing tutorials trying to learn C++ and am messing around with input and output fuctions and I thought I understood it quite well, but when I tried to write a simple code it doesn't seem to work properly. This is what I wrote.

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    int weight;
    int height;
    
    cout << "Please enter your height in inches: ";
    cin >> height;
    cout << "Please enter your weight in pounds: ";
    cin >> weight;
    cout << "Your Body-mass index is: ";
    cout << (weight / (height * height)) * 703;
    
    getch ();
    return 0;
}
It compiles and runs. It first asks for the height and then I input it. Then it asks for the weight, so I input it. The it says "Your Body-mass index is: 0." Why does it always come to zero no matter what I input? At firstI had another variable as int formula and had that fomula assigned that integer, but it also didn't work. I figured it was becuase it was above the input, so the formula was running before it had any input for what the integers were and it assigned 0 to them. But even when I moved it like this it still always gives me a zero. Can someone explaint his please. Thank you. Also. The actual formula has weight divided by height squared. I know height to the second power is the same as height x height, but is there a way of writing to the second, or third, or higher power in C++ instead of having to write it as height * height?? Thanks on this also.
Advertisement
use float

Or... You may try (703 * weight) / (height * height) but float will be more acurate
Because you are working with integer numbers.
Try changing 'int' to 'float' (or to 'double').
Thanks for the quick replys and yes float does work so thanks. Now why? Does int not work in this case because when it divides weight by (height * height) it goes into a very small decimal number and int doesn't support a decimal? or am I way off here? I just want/need to understand why it didn't work in the first place. Thanks again.

Anything on how to right squared, cubed, etc. without having to write height * height?

Emotions
Any time you do math with an int that is stored in an int, any decimal parts are just discared. So 1.34534 is 1, 0.987643 is 0. So in this case you have a number that was between 1 and 0. This would always be dropped down to zero.

theTroll
Alright that makes great sense. Since I was getting something like .3 or so when I divided weight by height ^ 2, it was being dropped to 0 so when I multiplied that by 703 I was get zero. Thanks alot.

This topic is closed to new replies.

Advertisement