Comp Sci What is the use of % in calculations? How can it be used to solve a calculation?

  • Thread starter Thread starter asz304
  • Start date Start date
  • Tags Tags
    C++
AI Thread Summary
The discussion focuses on the use of the modulus operator (%) in calculations, explaining that it yields the remainder from integer division. It clarifies that when mixing integers and doubles in operations, the result is promoted to the type with the highest precision, typically a double. Several examples illustrate how different operations yield varying results based on the order of operations and operand types. Additionally, there are inquiries about specific code snippets involving increment operators and function outputs, with explanations provided for the expected results. Overall, the thread emphasizes understanding type promotion and the behavior of arithmetic operations in programming.
asz304
Messages
107
Reaction score
0
What is the result of..
int*double=? Is it double?
int+double=? is it double too?

And...
What is "%" in a calculation? And how to solve the a calculation using "%"?
 
Physics news on Phys.org
asz304 said:
What is the result of..
int*double=? Is it double?
Yes.
asz304 said:
int+double=? is it double too?
Yes.
asz304 said:
And...
What is "%" in a calculation? And how to solve the a calculation using "%"?
This is the modulus operator. It is a binary (two operands) operator that evaluates to the remainder from integer division. For example, 7 % 5 == 2. If you divide 7 by 5, the (integer) quotient is 1, and the remainder is 2.
 
I can be wrong, but as far as I remember value of expression is always converted (promoted) up - that is, type of the result is that of highest precision number used in the expression. So, if you mix integeres and floats, the result will be always float.

However, it can be sometimes tricky - (4/5)*3.0 is 0.0, but (4*3.0)/5 is 2.4.
 
Last edited:
Borek's tricky examples sort of tie into your original question about th % operator, which itself is closely related to the concept of integer (vs floating point) division.

In C and C++ there are two kinds of division: integer and floating point. The same operator, /, is used for both, so the kind of division that is performed depends on the operands. If both operands are of an integer type (char, int, short, long), the result is integer division. The two operands can be of different integer types.

If at least one operand is a floating point type (float or double, typically), then the result is floating point division.

In Borek's first example, the parentheses cause the 4/5 to be evaluated, resulting in 0. Then 0 and 3.0 are multiplied, with 0 being promoted to a floating point (actually double) value, 0.0. 0.0 * 3.0 = 3.0.

In his second example, when 4 and 3.0 are multiplied, 4 is promoted to a double value, 4.0, making the multiplication evaluate to 12.0. When 12.0 is divided by 5, 5 is promoted to a double, resulting in the value 2.4 (or something close to it).
 
Thanks guys.

And I can't understand this...
int n, m;
n = 5;
m = n++;
cout<< m << “”<< n << endl;
m = ++n;
cout<< m << “”<< n << endl;

Are the outputs 6_5 and 6_5?

Please explain if I'm wrong. And why is the output of this code fum(4) = 6
double fum(int i);

int main(){
int i = 4;
cout << "fum(" << i << ") is " << fum(i);
return 0;
}

double fum(int i) {
double x = 1.0;
for( int j = 1; j < i; j++)
x*=j;
return x;
}Output = fum(4) is 6
 
Last edited:
asz304 said:
Thanks guys.

And I can't understand this...
int n, m;
n = 5;
m = n++;
cout<< m << “”<< n << endl;
m = ++n;
cout<< m << “”<< n << endl;

Are the outputs 6_5 and 6_5?

Please explain if I'm wrong.
In the first cout, m is 5 and n is 6. The value of n (5) is stored in m, and then n is post-incremented, so the output is 56 or maybe 5 6.

In the statement m = ++n, n is pre-incremented (to 7), and the value stored in m, so the output is 77 or maybe 7 7.
asz304 said:
And why is the output of this code fum(4) = 6
double fum(int i);

int main(){
int i = 4;
cout << "fum(" << i << ") is " << fum(i);
return 0;
}

double fum(int i) {
double x = 1.0;
for( int j = 1; j < i; j++)
x*=j;
return x;
}


Output = fum(4) is 6

Work this out for yourself. When fum is called, the value 4 is passed in the call. For what values of j will the loop execute?
 
Mark44 said:
In the first cout, m is 5 and n is 6. The value of n (5) is stored in m, and then n is post-incremented, so the output is 56 or maybe 5 6.

In the statement m = ++n, n is pre-incremented (to 7), and the value stored in m, so the output is 77 or maybe 7 7.

m = ++n means 2 + n ?In this code, why is it that double taxCalc(double); is declared instead of double taxCalc( double taxableIncome)? Is it because taxCalc(double) will also be used in the body of the main as taxCalc(income)?#include <iostream>
using namespace std;

double taxCalc(double);

int main() {
double income;
double dueTax;

cout<< "Enter your taxable income: ";
cin >> income;

dueTax = taxCalc(income);
cout << "\nThe tax is " << dueTax << endl;

return 0;
}

/** taxCalc **************************
*
* @params: dInc - a valid taxable income
* @pre: must be non-negative
*
* @returns: due tax (double)
***************************************************/
double taxCalc(double taxableIncome)
{
double tax;
if (taxableIncome <= 29590) {
tax = 0.17 * taxableIncome;
}
else {
if (taxableIncome <= 59180) {
tax = 5030 + 0.26 * (taxableIncome - 29590);
}
else {
tax = 12724 + 0.29 * (taxableIncome - 59180);
}
}
return tax;
}
 
Last edited:
asz304 said:
m = ++n means 2 + n ?
No. It means two things: increment n, and store the incremented value in m.
asz304 said:
In this code, why is it that double taxCalc(double); is declared instead of double taxCalc( double taxableIncome)? Is it because taxCalc(double) will also be used in the body of the main as taxCalc(income)?
For the prototype of a function, you can include the names of parameters or you can omit them. If you include parameter names, they can be the same as or different from the names of the parameters as used in the function definition.
asz304 said:
#include <iostream>
using namespace std;

double taxCalc(double);

int main() {
double income;
double dueTax;

cout<< "Enter your taxable income: ";
cin >> income;

dueTax = taxCalc(income);
cout << "\nThe tax is " << dueTax << endl;

return 0;
}

/** taxCalc **************************
*
* @params: dInc - a valid taxable income
* @pre: must be non-negative
*
* @returns: due tax (double)
***************************************************/
double taxCalc(double taxableIncome)
{
double tax;
if (taxableIncome <= 29590) {
tax = 0.17 * taxableIncome;
}
else {
if (taxableIncome <= 59180) {
tax = 5030 + 0.26 * (taxableIncome - 29590);
}
else {
tax = 12724 + 0.29 * (taxableIncome - 59180);
}
}
return tax;
}
 
I'm doing this new assignment and I'm stuck so far in calculating for the 2k Race time... and I dunnu how to grab string values..All I know is on my work, and that I will use If and else statement for outputing Gold time Record. Could anyone tell me what I should do next? Thanks

Source:http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/10/19_Assignment_4__Mike_Spracklen_Needs_your_help!.html"

My work:
#include <iostream>
#include <string>
using namespace std;

float atof ( number.c_str());

int main()
{
string event;
string splitTime;
int spacePos = 0;

cout << " Enter the the event type( 2-, 2x or 1x): ";
cin >> event;
cout << " The event type is: " << event << endl;

cout << " Enter the split time in/500m (mm:ss:s): " << endl;
cin >> splitTime;
cout << " The split time is: " << splitTime << endl;

}
 
Last edited by a moderator:
  • #10
Take a look at the hints your instructor gave:
Hints:

*There are a number of ways to calculate total race time from split time. If you can't figure it out try solving the problem on paper first. Remember, split time is time/500m.

*You can use the string functions discussed in class to split the time at the ":" character to get separate strings for minutes and seconds. If you don't remember how to do this, look at Dr. Zhang's example of splitting using the '*' character.

*Getting a number from a string can be tricky. Fortunately, there's an easy way that you can do this using a function called "atof" and the std::string's c_str() function. To get a floating point from a string called "number" you would do this: "double myVal = atof( number.c_str() );" There are other ways of doing this, but this is the easiest for now. Note: to use atof you may need to include the c standard library by using "#include <cstdlib>"

*Like all programming, the key to success in this assignment will be breaking the problem down into it's component pieces.


*Ensure that you follow the submission guidelines.
 
  • #11
*The only error I have is this statement/ expression "cout << " 2k Race Time is: " << raceTime/60 <<':'<<raceTime%60 << endl;" and it says invalid operands of double and int into the binary operator % .

*When I ran the program it just included the first two cout statements. and after I input the split time..nothing happens. Is it because of my problem that i stated at the first part above?Here's my code:

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std; void goldStandard (string event, double raceTime );

/********************************************************************************************************************
* @params: none
* @descript: Gets input values "event" and " splitTime" from the user and outputs the calculations for 2k Race Time
* and tells whether it is a gold standard time.
* @returns: 0 for succession
********************************************************************************************************************/
int main()
{
double myValueofMinutes, myValueofSeconds; // extracting of minute and seconds using functions of atof
string event; // type of the boat
string splitTime;
string minutes, seconds; // separation of minutes and seconds from split times
double raceTime;
int index;
string goldTime; cout << " Enter the type of event (2-, 2x or 1x): ";
cin >> event;
cout << " The event type is: " << event << endl;

cout << " Enter the split time in/500m (mm:ss.s): " << endl;
cin >> splitTime;
cout << " The split time is: " << splitTime << endl; index = splitTime.find(':',0 ); // index = 3
minutes = splitTime.substr(0, index); //minutes = mm ( which is minutes that will be inputed from the user )
seconds = splitTime.substr ( index + 1); // seconds = "ss.s" ( which is seconds with a decimal point )

myValueofMinutes = atof (minutes.c_str ());
myValueofSeconds = atof (seconds.c_str ());

raceTime = ( myValueofMinutes*60 + myValueofSeconds*60 )*4 ;
goldStandard ( event, raceTime );

cout << " 2k Race Time is: " << raceTime/60 <<':'<<raceTime%60 << endl;

return 0;
}

/********************************************************************************************************
* @params: string event - is the event type value given by the user
*
* @descript: Tells if the time of a specific boat type is a gold standard time
*
* @returns: record - to return the calculations into the main function
********************************************************************************************************/
void goldStandard(string event, double raceTime )
{
if ( event == "1x" && raceTime <= 393 )
cout << "\nIt's a Gold Standard Time!";

else if ( event == "2x" && raceTime <= 362 )
cout << "\nIt's a Gold Standard Time!";

else if ( event == "2-" && raceTime <= 373 )
cout << "\nIt's a Gold Standard Time!";

else;
}
 
Last edited:
  • #12
asz304 said:
*The only error I have is this statement/ expression "cout << " 2k Race Time is: " << raceTime/60 <<':'<<raceTime%60 << endl;" and it says invalid operands of double and int into the binary operator % .
You can't use the modulus operator with one or more real (i.e., float or double) operands.

I don't see why you are using the double type for your raceTime variable. Instead of using atof to convert from a string to a double, use atoi to convert the minutes and seconds strings to int values.

asz304 said:
*When I ran the program it just included the first two cout statements. and after I input the split time..nothing happens. Is it because of my problem that i stated at the first part above?


Here's my code:

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


void goldStandard (string event, double raceTime );

/********************************************************************************************************************
* @params: none
* @descript: Gets input values "event" and " splitTime" from the user and outputs the calculations for 2k Race Time
* and tells whether it is a gold standard time.
* @returns: 0 for succession
********************************************************************************************************************/
int main()
{
double myValueofMinutes, myValueofSeconds; // extracting of minute and seconds using functions of atof
string event; // type of the boat
string splitTime;
string minutes, seconds; // separation of minutes and seconds from split times
double raceTime;
int index;
string goldTime;


cout << " Enter the type of event (2-, 2x or 1x): ";
cin >> event;
cout << " The event type is: " << event << endl;

cout << " Enter the split time in/500m (mm:ss.s): " << endl;
cin >> splitTime;
cout << " The split time is: " << splitTime << endl;


index = splitTime.find(':',0 ); // index = 3
minutes = splitTime.substr(0, index); //minutes = mm ( which is minutes that will be inputed from the user )
seconds = splitTime.substr ( index + 1); // seconds = "ss.s" ( which is seconds with a decimal point )

myValueofMinutes = atof (minutes.c_str ());
myValueofSeconds = atof (seconds.c_str ());

raceTime = ( myValueofMinutes*60 + myValueofSeconds*60 )*4 ;
goldStandard ( event, raceTime );

cout << " 2k Race Time is: " << raceTime/60 <<':'<<raceTime%60 << endl;

return 0;
}

/********************************************************************************************************
* @params: string event - is the event type value given by the user
*
* @descript: Tells if the time of a specific boat type is a gold standard time
*
* @returns: record - to return the calculations into the main function
********************************************************************************************************/
void goldStandard(string event, double raceTime )
{
if ( event == "1x" && raceTime <= 393 )
cout << "\nIt's a Gold Standard Time!";

else if ( event == "2x" && raceTime <= 362 )
cout << "\nIt's a Gold Standard Time!";

else if ( event == "2-" && raceTime <= 373 )
cout << "\nIt's a Gold Standard Time!";

else;
}
 
  • #13
But my instructor told my class to use atof. So should I just change my raceTime to int?
 
  • #14
I can't imagine that he would dock you for using atoi instead of atof, but if you're in doubt, check with him.

Yes, I would make raceTime an int.
 
  • #15
atof and atoi works well. The only problem I have now is that my program doesn't output "It's a standard gold time!", and raceTime has the correct calculations. Thanks
 
  • #16
You can't compare strings using ==, which is what your goldStandard function is doing. Instead, use the compare method in the string class. See http://www.cplusplus.com/reference/string/string/compare/.

I'm not very familiar with how a string is implemented in the string class, so I can't say for sure what is happening when you try to do a comparison such as event == "2x".

The way that string literals work in C is that a comparison such as event == "2x" is that they compare the locations in memory of the two things. In C, the expression event == "2x" (where event is declared as char * or char[]) evaluates to true if the location in memory of event is the same as the location in memory of the literal "2x", which is pretty much never true.
 
Last edited by a moderator:
  • #17
I have this new assignment that's fun, but like always I got problems :D

Code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

const int VANCOUVER = 4;
const int SANFRAN = 3;
const int TORONTO = 2;
const int MONTREAL = 1;
const int DEFAULT = 0;

float timeVancouver (int);
float timeSanfran(int);
float timeToronto(int);
float timeMontreal(int);
void displayMessage ();

/*****************************************************************************************************
*@params: none
*
*@descript: Displays choices to the user to choose from, then the program does the required
* operations to display the current time of the user's choice.
*
*@returns: 0 for succession
****************************************************************************************************/
int main ()
{
int time; // Time inputed from the user with the desired choice
string localTime; // Time in St. John's
string hours, minutes;
int index;
int totalTime, myValueofHours, myValueofMinutes;
char option; // choices for the user to choose

cout << " Please choose your city: ";
cout << " \na- Vancouver, BC ";
cout << " \nb-San Fran, Ca ";
cout << " \nc-Toronto, ON ";
cout << " \nd-Montreal, QC ";
cout << " \nq-Quit ";
cout << " \nChoose an option [abcdq] ";
cin >> option;
cout << " Enter local time in St. John's ( hh:mm ): ";
cin >> localTime;

index = localTime.find(':',0); // index = 3
hours = localTime.substr (0,index); // is hh ( hours ) from localTime
minutes = localTime.substr ( index + 1 ); // is mm ( minutes ) from localTime

myValueofHours = atof ( hours.c_str());
myValueofMinutes = atof ( minutes.c_str());

totalTime = ( myValueofHours*60 + myValueofMinutes/60 );

switch ( option ){
case 'a':
timeVancouver(totalTime);
time = VANCOUVER;
break;
case 'b':
timeSanfran(totalTime);
time = SANFRAN;
break;
case 'c':
timeToronto(totalTime);
time = TORONTO;
break;
case 'd':
timeMontreal(totalTime);
time = MONTREAL;
break;
default:
displayMessage();
time = DEFAULT;

}

return 0;
}

/*****************************************************************************************************
*@params: totalTime - total time of stringed minutes and seconds from "string localTime"
*
*@descript: Calculates the time in Vancouver from St. John's using Pacific Time
*
*@returns: calculated local time for Vancouver
*
****************************************************************************************************/
float timeVancouver (int totalTime)
{
cout << "\nLocal time in Vancouver is: " << totalTime + 8;

return VANCOUVER;
}

/****************************************************************************************************
* @params: totalTime - total time of stringed minutes and seconds from "string localTime"
*
* @descript: Calculates the time in San Fransisco from St. John's using Pacific time
*
* @returns: SANFRAN - calculated local time for San Fransisco
*
****************************************************************************************************/
float timeSanfran(int totalTime)
{
cout << "\nLocal time in San Fransisco is: " << totalTime + 8;

return SANFRAN;
}
/****************************************************************************************************
* @params: totalTime - total time of stringed minutes and seconds from "string localTime"
*
* @descript: Calculates the time in Toronto from St. John's using Eastern Standard Time.
*
* @returns: calculated local time for Toronto
*
****************************************************************************************************/
float timeToronto(int totalTime)
{
cout << "\nLocal time in Toronto is: " << totalTime + 5;

return TORONTO;
}
/****************************************************************************************************
* @params: totalTime - total time of stringed minutes and seconds from "string localTime"
*
* @descript: Calculates the time in Montreal from St. John's using Eastern Standard time.
*
* @returns: calculated local time for Montreal
*
****************************************************************************************************/
float timeMontreal(int totalTime)
{
cout << "\nLocal time in Montreal is:"<< totalTime + 5;

return MONTREAL;
}
/****************************************************************************************************
* @params: none
*
* @descript: Outputs this message if the user inputs a bad choice. ( ie. i, j )
*
****************************************************************************************************/
void displayMessage ()
{
cout << "\nRe-enter the right choices[abcdq]";
}

Source:http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/10/25_Assignment_5__Tell_em_What_Time_it_is..htmlIn this assignment. I can't get the right calculations for time in several places. And is my formula for totalTime and time(CITY) right?
Thanks
 
  • #18
As I write this, it is 7:30am my time (PST) and 12:00 noon in St. John's, so for a given time in St. John's, you would subtract 4 1/2 hours to get the time on the West Coast of the US, not add 8 hours. Here's a link to where I found this information: http://www.timeanddate.com/library/abbreviations/timezones/na/ndt.html.

Your formula for totalTime is incorrect.
Code:
totalTime = ( myValueofHours*60 + myValueofMinutes/60 );

Apparently you intend for totalTime to be in minutes, so multiply the number of hours by 60 and then add the number of minutes (don't divide the minutes by 60).

Why are you using atof to convert the hours and minutes strings? atof converts a string of digits to double, not float. Your variables for the times in the various cities are type float, not double, so you have a mismatch of types between the output of atof and the variables used to hold the times for the cities. It makes more sense to me to use atoi to convert the hours and minutes strings, and to store the time for each of the cities in an int. I don't see any need for float or double variables in this problem.
 
  • #19
Sixth Assignment:

So I dunnu which is easier to do..using for loop or recursion( didn't take it yet ), and how do I make an input example 5sigma into 35 number of glasses by string? should levels be string instead of int? And I don't know how to make the formula to work...

Source : http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/11/2_Assignment_6__Pyramids_o_Celebration.html

My Code: When I run my code, it doesn't stop outputting if I press q. How to fix it? Thanks

int main (){
int levels;
int glasses;

while( levels != 'q' ){

cout << " Enter the number of levels or ( q to quit ): ";
cin >> levels;

cout << "You need" << glasses << "glasses for this pyramid" << endl;
}

switch ( levels ){
case 'q':
quitProgram ();
break;
default:
displayMessage();
levels = DEFAULT;
break;
}

return 0;
}

/***********************************************************************************************************
*
* @params:
*
* @descript: factors/calculates the number of glasses in a certain level from the pyramid.
*
* @returns: the factorial of the total number of glasses in a certain level from the pyramid.
*
********************************************************************************************************/\

int factorial ( int levels )

{
if ( levels >= 1 ) return 1;
return levels*factorial( levels + 1 );
}

/*********************************************************************************************************
*
* @params: none
*
* @descript: Outputs this message if the user inputs a bad input.
*
********************************************************************************************************/

void displayMessage()
{
cout << "\nHelp: Enter a positive integer or q to quit.";
}
/*******************************************************************************************************
*
* @params: none
*
* @descript: Quits program if the user inputs q.
*
******************************************************************************************************/

void quitProgram()
{

}
 
  • #20
I'll first point out that you don't use a factorial for this problem

if you use a factorial level 4 needs 24 glasses (4*3*2*1)
but the problem says it should be 10 (4 + 3 + 2 + 1)

even if you needed to use factorials your function doesn't work correctly

say I wanted the factorial of 4 your function would return 1 and then stop !

I think that itd be much easier to use a for loop than recursion for adding up all numbers less than n or for the factorial (although keep in mind there is a handy and simply formula for adding up all the numbers up to n).Also, the way you have the loop set up you don't ever get an error message when you enter an invalid input

dont know what 5sigma means
 
  • #21
7th assignment:

I'm not sure of my work in the part of the strings and stuff when finding the components of height. And my calculations are wrong..Thanks

Source: http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/11/9_Assignment_7__Get_Rich_Quick_Scheme_3%2C241%2C368_-_Fitness_Software.html

My code :
Code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

/***************************************************************************************************
 *
 * @params: none
 *
 * @descript: Asks inputs from the user ( weight, height, age, and sex ) with the desired number of unites
 *            then the program does the required work( such as conversion from one unit to another )
 *            to calculate for BMR and BMI.
 *
 * @returns: 0 for succession.
 *
 ***************************************************************************************************/

int main()
{
	string weight, height;
	float age;
	int indexWeight, indexHeight;
	char sex;
	string mass, massUnits, height1, height2, heightUnits1, heightUnits2;
	float myValueofMass, myValueofWeight;
	float heightValue, heightValue2, myValueofHeight1, myValueOfHeight2, myValueofHeight2, myValueofHeight, BMR, BMI;

		cout << "\nEnter mass: [in kg orlbs ]";
		getline ( cin, weight );

				indexWeight = weight.find ( ' ', 0 );	// index depends on the number of digits that the user provided
				mass = weight.substr (0, indexWeight );
				massUnits = weight.substr ( indexWeight + 1);

					myValueofMass = atof ( mass.c_str () );

				if ( massUnits == "lbs" ){
					myValueofWeight = myValueofMass*0.4535923; // 0.4535923 is the conversion factor for lbs to kg
				}

		cout << "\nEnter height: [in cm or with the unit of inch]:";
		getline ( cin, height );

		        indexHeight = height.find ( ' ', 0 );
		        height1 = height.substr ( 0, indexHeight );
	    	//    height2 = height.substr ( 0, );
		        heightUnits1 = height.substr ( indexHeight + 1 );
		        heightUnits2 = height.substr ( indexHeight + 2 );

		        	myValueofHeight1 = atof ( height1.c_str() );
		        	myValueofHeight2 = atof ( height2.c_str() );

		        if ( heightUnits1 == " ' " ){
		        	heightValue = myValueofHeight1*30.48;
				}

	            if ( heightUnits2 == " \" "){
	            	heightValue2 =  myValueOfHeight2*2.54;
	            }

		        myValueofHeight = heightValue + heightValue2;

		cout << "\nAge: [ in years ]:";
		cin >> age;
		cout << "\nSex: [m or f]";\
		cin >> sex;

			if (sex == 'm'){
				sex = 5;
			}
			else{
				sex = -161;
			}

		BMR = 6.25*myValueofHeight + 10.0*myValueofWeight + 5.0*age + sex;

		BMI = myValueofWeight /(myValueofHeight*myValueofHeight);

		cout << "\nCalculating for " << weight << " and " << height;
		cout << "\nEstimated BMR: " << BMR << "kcal/day" << endl;
		cout << "Estimated BMI: " << BMI << endl;

	return 0;
}
 
  • #22
I formatted your code to eliminate unnecessary indentation.
asz304 said:
7th assignment:

I'm not sure of my work in the part of the strings and stuff when finding the components of height. And my calculations are wrong..Thanks

Source: http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/11/9_Assignment_7__Get_Rich_Quick_Scheme_3%2C241%2C368_-_Fitness_Software.html

My code :
Code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

/***************************************************************************************************
 *
 * @params: none
 *
 * @descript: Asks inputs from the user ( weight, height, age, and sex ) with the desired number of unites
 *            then the program does the required work( such as conversion from one unit to another )
 *            to calculate for BMR and BMI.
 *
 * @returns: 0 for succession.
 *
 ***************************************************************************************************/

int main()
{
	string weight, height;
	float age;
	int indexWeight, indexHeight;
	char sex;
	string mass, massUnits, height1, height2, heightUnits1, heightUnits2;
	float myValueofMass, myValueofWeight;
	float heightValue, heightValue2, myValueofHeight1, myValueOfHeight2, myValueofHeight2, myValueofHeight, BMR, BMI;

	cout << "\nEnter mass: [in kg orlbs ]";
	getline ( cin, weight );
	indexWeight = weight.find ( ' ', 0 );	// index depends on the number of digits that the user provided
	mass = weight.substr (0, indexWeight );
	massUnits = weight.substr ( indexWeight + 1);

	myValueofMass = atof ( mass.c_str () );

	if ( massUnits == "lbs" ){
		myValueofWeight = myValueofMass*0.4535923; // 0.4535923 is the conversion factor for lbs to kg
	}

	cout << "\nEnter height: [in cm or with the unit of inch]:";
	getline ( cin, height );

	indexHeight = height.find ( ' ', 0 );
	height1 = height.substr ( 0, indexHeight );
	//    height2 = height.substr ( 0, );
	heightUnits1 = height.substr ( indexHeight + 1 );
	heightUnits2 = height.substr ( indexHeight + 2 );

	myValueofHeight1 = atof ( height1.c_str() );
	myValueofHeight2 = atof ( height2.c_str() );

	if ( heightUnits1 == " ' " ){
	      	heightValue = myValueofHeight1*30.48;
	}

	if ( heightUnits2 == " \" "){
	            	heightValue2 =  myValueOfHeight2*2.54;
	}

	myValueofHeight = heightValue + heightValue2;

	cout << "\nAge: [ in years ]:";
	cin >> age;
	cout << "\nSex: [m or f]";\
	cin >> sex;

	if (sex == 'm'){
		sex = 5;
	}
	else{
		sex = -161;
	}

	BMR = 6.25*myValueofHeight + 10.0*myValueofWeight + 5.0*age + sex;

	BMI = myValueofWeight /(myValueofHeight*myValueofHeight);

	cout << "\nCalculating for " << weight << " and " << height;
	cout << "\nEstimated BMR: " << BMR << "kcal/day" << endl;
	cout << "Estimated BMI: " << BMI << endl;

	return 0;
}

What problems are you having? What makes you think your calculations are wrong?
 
  • #23
This part probably makes my calculations wrong
Code:
indexHeight = height.find ( ' ', 0 );
	height1 = height.substr ( 0, indexHeight );
	//    height2 = height.substr ( 0, );
	heightUnits1 = height.substr ( indexHeight + 1 );
	heightUnits2 = height.substr ( indexHeight + 2 );

	myValueofHeight1 = atof ( height1.c_str() );
	myValueofHeight2 = atof ( height2.c_str() );

	if ( heightUnits1 == " ' " ){
	      	heightValue = myValueofHeight1*30.48;
	}

	if ( heightUnits2 == " \" "){
	            	heightValue2 =  myValueOfHeight2*2.54;
	}

	myValueofHeight = heightValue + heightValue2;


I did the exact inputs from this example:Sample Output #2:

Enter weight [in kg or lbs]: 47 kg

Enter height [ in cm or in ' and "]: 157 cm

Enter age [in years]: 38

Enter sex [m or f]: f

Calculating for 47 kg and 157 cm

Estimated BMR: 1480.25 kcal/day

Estimated BMI: 19.0677


And tried another one with these inputs:
Enter weight [in kg or lbs]: 184 lbs

Enter height [ in cm or in ' and "]: 6' 0"

Enter age [in years]: 36

Enter sex [m or f]: m

Calculating for 83.461 kg and 182.88 cm

Estimated BMR: 2162.61 kcal/day

Estimated BMI: 24.9546

But got wrong outputs from both examples. [ Examples were derived from http://www.engr.mun.ca/~markevans/engr1020/Eng1020Labs/Assignments/Entries/2010/11/9_Assignment_7__Get_Rich_Quick_Scheme_3%2C241%2C368_-_Fitness_Software.html]

BMI gave a value of 0. I have a doubt about the part with ' and " for feet and inches I dunnu what to do with height2
Code:
height1 = height.substr ( 0, indexHeight );
	//    height2 = height.substr ( 0, );
	heightUnits1 = height.substr ( indexHeight + 1 );
	heightUnits2 = height.substr ( indexHeight + 2 );
 
Last edited by a moderator:
  • #24
Since you got a BMI of 0, that means that myValueofWeight has to be 0. Looking at your code, myValueofWeight gets its value in this code:
Code:
if ( massUnits == "lbs" ){
		myValueofWeight = myValueofMass*0.4535923; // 0.4535923 is the conversion factor for lbs to kg
	}
1. You can't compare strings using ==. You can write code that does this, but you will get the wrong answer. How else can you check two strings to see if they are the same? Your instructor and text should have said something about this.
2. What happens if massUnits is not in units of pounds? In this case myUnitsofWeight won't get a value, so you won't get the right value for BMI.

If you are in doubt about the value of any variables, add some cout statements in your code to print the values. When things are working correctly, you can take out those cout statements. This is one of the oldest debugging techniques. You should use it, especially if you don't know how to use a debugger.
 
  • #25
One other thing. When you have a new question, start a new thread. Don't just keep tacking new problems onto an existing thread.
 
Back
Top