I'm new to these forums and also to C++. I started experimenting a bit yesterday and today i made my first *useful* program. It is a BMI calculator.I know it is in dutch, but that shouldn't change the behavior of the program (I think?).
I would like to know if I programmed unnecessary parts or if I could do it easier/cleaner.
//operating with variables
#include <iostream>
usingnamespace std;
int main ()
{
//declaring variables
float a,b ;
float result ;
//process
cout<< "geef je gewicht op \n";
cin>> a;
cin.ignore ();
cout<< "geef je lengte op in meter \n";
cin>> b ;
cin.ignore ();
result = a / (b*b);
//result
if (result < 17.5) {
cout<< "Je BMI is "<< result <<". Je hebt ondergewicht.";
}
elseif (result < 24.99) {
cout<< "Je BMI is "<< result <<" . Je bent normaal.";
}
elseif (result < 29.99) {
cout<< "Je BMI is "<< result <<" . Je hebt overgewicht.";
}
elseif (result > 29.99) {
cout<< "Je BMI is "<< result <<" . Je hebt ernstig overgewicht. Laat je testen op Obesitas.";
}
cin.get ();
}
Hello to you too. Nice one, well done! :D Most people declare their variables as ints and then have trouble with the division operation, but it seems that you haven't fallen to this trap. I have a few suggestions though:
#include <iostream>
usingnamespace std;
//make a string table with the bmi descriptions
constchar * bmi_description[]=
{"Je hebt ondergewicht.","Je bent normaal.",
"Je hebt overgewicht.","Je hebt ernstig overgewicht."" Laat je testen op Obesitas."};
int main ()
{
//declaring variables
float a,b ;
float result ;
//process
cout<< "geef je gewicht op \n";
cin>> a;
//cin.ignore (); //<- this will only ingore one char
//I usually do it like this:
while(cin.get()!='\n');
cout<< "geef je lengte op in meter \n";
cin>> b ;
//cin.ignore (); //same here
while(cin.get()!='\n');
//result
result = a / (b*b);
//declare a variable to hold the bmi class
//and set its value depending on the result
int bmi_class;
if (result < 17.5) bmi_class=0;
elseif (result < 24.99) bmi_class=1;
elseif (result < 29.99) bmi_class=2;
else /*if (result > 29.99) (<-you can omit this)*/ bmi_class=3;
//print the results
cout<< "Je BMI is "<< result <<" . " << bmi_description[bmi_class];
cin.get ();
return 0;
}
He used a pointer to a character array to store the descriptions. You can also use a string array and it is much easier. But dont forget to use use #include<string>
1 2 3
std::string[] = {"Je hebt ondergewicht.","Je bent normaal.",
"Je hebt overgewicht.","Je hebt ernstig overgewicht."" Laat je testen op Obesitas."};