Subtraction is giving me positive result C++ - c++

if (GoalWeight < 0.0) {
int weeks;
cout << "How many weeks do you plan to continue this trend?\n";
cin >> weeks;
double NewWeight = GoalWeight * weeks;
double NegBMI = (weight - NewWeight) * 703 / (pow(HeightConverter, 2));
cout << "If you complete your plan for " << weeks << "weeks you will have a new BMI of: \n" << NegBMI;
}
system("pause");
return 0;
}
Output result:
What is your current weight?: 180
What is your current height in inches?" 71
Your current BMI is: 25.10(Not part of output, but this is correct)
What is your goal weight change?(lbs) -1.5
How many weeks do you plan to continue this trend?: 6
If you complete your plan for 6 weeks you will have a new BMI of: 26.36
As you can tell this is wrong
The calculation for BMI is (weight * 703) /height^2(inches)
What it is doing for negative numbers is:
180 + 9(instead of 180 - 9) giving (191 * 703) / 71^2 yielding 26.36
Instead of:
180 - 9(giving 171 * 703) / 71^2 yielding the correct output of:23.84
I know you're all shaking your heads saying I must be an idiot, and rightfully so, I'm hoping someone can help me with this!

What is your goal weight change?(lbs) -1.5
How many weeks do you plan to continue this trend?: 6
6 * ( -1.5 ) == -9
180 - (-9) == 189
So you either input goal weight change as positive number or add it, not subtract.

Your newWeight is resulting to -9 because of your statement 6 * -1.5.If you want to subtract it just make the (weight + newWeight) rather than the -.

Do you believe that if you do (+NewWeight) the value of NewWeight becomes positive?
this is not the case:
Unary Plus Operator (+): The result of an operation on a numeric type is the value of the operand itself. This operator has been predefined for all numeric types.
As a solution use Reginalds idea and make (weight + newWeight) rather than the -.

Related

Trigonometric Equation only works with specific input ( 5 ) doesn't work with other inputs

I try to write code for that calculation angles from lengths of triangle. formula is
cos(a)=b^2+c^2-a^2/2bc. (Triangle is here)
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;
angle2 = acosf((powf(length1,2) + powf(length3,2) - powf(length2,2)) / 2 * length1 * length3)* 180 / 3.14153;
angle3 = 180 - (angle2 + angle1);
Everything is float. When entered 5-4-3 inputs outcome this.
angle one is 90.0018
angle two is nan
angle three is nan
changing order doesn't matter, only gives output for 5.
You are doing:
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;
You should be doing:
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / (2 * length2 * length3))* 180 / 3.14153;
Explanation: The problem is caused by the following formula, which is in fact badly written:
cos(a)=b^2+c^2-a^2/2bc
// This, obviously, is wrong because
// you need to group the firt three terms together.
// Next to that, everybody understands that the last "b" and "c" are divisors,
// yet it would be better to write it as:
cos(a)=(b^2+c^2-a^2)/(2bc)
The brackets, I added in the code, are similar to the replacement of /2bc by /(2bc).

Trying to get an "adjusted" ratio of two numbers

I would like to do this
I have two numbers, A and B, where it can be A greater or smaller than B. What I want to do:
Compare B with A
If their ratio is "ouside" of a range, then take a random number and add it to "A" - Now check if their new ratio meets the condition
0.95 < ratio < 1.05
if not, try with another random.
My problem is that I ran into infinite loops... this is what I do:
float ratio = A/B;
if (ratio < 0.95 || ratio > 1.05) {
do {
// randomly take a negative or positive number
float random_n = ((float)rand())/RAND_MAX - 0.50;
// get an even smaller step
random_n *= 0.1;
// add or subtract the random number (depending on its sign)
A += random_n;
// form the ratio again
ratio = A / B;
cout << "lets see " << A << " " << B << " " << ratio << endl;
}
while (ratio > 0.95 || ratio < 1.05);
}
The condition should be:
while (ratio <= 0.95 || ratio >= 1.05);
You got the "<" and ">" mixed up. ratio is not between 0.95 and 1.05 if it's less or equal than 0.95 or greater or equal than 1.05.
It's easy to avoid such mistakes if you remember how you negate a conjunction:
NOT (0.95 < ratio < 1.05) === NOT (0.95 < ratio AND ratio < 1.05) ====
[...]
The rule is: change every AND to OR and negate all sub-expressions:
[...] === (NOT (0.95 < ratio) OR NOT (ratio < 1.05)) ====
(0.95 >= ratio OR ratio >= 1.05) === (ratio <= 0.95 OR ratio >= 1.05)
Your do..while loop condition should be
while(ratio <= 0.95 || ratio =>1.05)
Well the problem is you're increasing A and never changing B
and still expect ratio to be in (0.95,1.05) . This depends on initial value of A and B to break the loop.
Try:
B=rand()%RAND_MAX;
do {
A=rand()%RAND_MAX;
ratio = A/B;
cout<<"lets see "<< A <<" "<< B <<" "<<ratio<<endl;
}while(ratio <0.95 || ratio>1.05);
Then can divide A and B by power of ten as per your needs.
Also use srand(time(0)) for different random values on successive runs

C++ Weird Variable Issues

I'm using the following code to calculate and display the final score for a math game in C++.
int score = (correctNumber / 3) * 100;
cout << score;
The variable "correctNumber" is always a value between 0 and 3. However, unless "correctNumber" = 3, then the variable "score" always equals "0". When "correctNumber" equals 3 then "score" equals 100.
Say "correctNumber" was equal to 2. Shouldn't "score" be 67 then? Is this some issue with int variable type being unable to calculate decimal points?
You are doing math as integer so 1 / 3 is 0.
Try:
int score = (100 * correctNumber) / 3
and if you want to round:
int score = (100 * correctNumber + 1) / 3
I'm assuming correctNumber is an int, based on what you described. What's happening is integer truncation. When you divide an int by an int, the result always rounds down:
1/3 = 0.3333 = 0 as an integer
2/3 = 0.6667 = 0 as an integer
3/3 = 1.0000 = 1 as an integer
The easy way to remedy this here is to multiply it first:
int score = correctNumber * 100 / 3;
However, this still leaves you with 66 for 2, not 67. A clear and simple way of dealing with that (and many other rounding situations, though the rounding style is unconfigurable) is std::round, included since C++11:
int score = std::round(currentNumber * 100. / 3);
In the example, the dot in 100. makes 100 a double (it's the same thing as 100.0), so the result of the operation will be the floating-point value you want, not a pre-truncated value passed in as a floating-point value. That means you'll end up with 66.66666... going into std::round instead of 66.
Your guess is correct. int can't store real numbers.
But you can multiply first, and then divide, like
score = correctNumber * 100 / 3;
score will have 0, 33, 66, 100, depending on values of correctNumber
The problem is that (correctNumber / 3) is an integer, so you can't get 0.666 or any fraction to multiply by 100, which what I believe is you want.
You could try to force it to be a float like this:
int score = ((float)correctNumber / 3) * 100;
This, however, will give you 66 instead of 67, cause it doesn't round up. You could use C99 round() for that.
int score = round(((float)correctNumber / 3) * 100);
UPDATE:
You can also use + 0.5 to round, like this:
int score = (correctNumber / 3.0f) * 100.0f + 0.5f;

trouble using an equation in a function

Write a program that determines how far and for how long a time a rock will travel when you throw it off a cliff. Click here to copy the file toss.txt to your desktop (right click the file name and choose Save as). The file contains the height of the cliff in meters.
The program will then:
Open the file toss.txt and read the cliff height into a double-precision variable, then echo print the value of the cliff height to the screen with an appropriate label.
Ask the user for the angle at which the rock is thrown (90 degrees is straight up, and 0 degrees is straight forward), and the velocity at which the rock is thrown (in miles per hour).
Check to make sure the angle is greater than or equal to 0 and less than or equal to 90. If it is not, the program terminates and prints an appropriate error message to the screen.
Check to make sure the velocity is less than or equal to 100 mph and greater than or equal to 0 mph. If it is not, the program terminates and prints an appropriate error message to the screen.
If the angle and velocity are valid, the program completes the calculations as follows:
Converts miles per hour to meters per second.
Converts the angle to radians.
Calculates the time traveled using the following equations:
where
Calculates the distance traveled in the horizontal direction using:
Outputs the time and distance traveled in the horizontal direction to the screen with appropriate labels.
Prints an appropriate message telling the user if the distance traveled in the horizontal direction was greater than, less than, or equal to the height of the cliff.
/* This program */
using namespace std;
#include<iostream>
#include<cmath>
#include<iomanip>
#include<fstream>
int readit ();
int calcit (double, double, double);
int main()
{
readit ();
system ("pause");
return 0;
}
int readit ()
{
double hite, angl, v;
ifstream datain ( "toss.txt" );
datain >> hite;
cout << "The cliff height is " << hite << " meters"<< endl;
cout << "Enter the angle in degrees (from horizontal) the rock is thrown: "
<< endl;
cin >> angl;
if (angl>=0 && angl<=90)
{
cout << endl << "The angle you have entered is "<<angl<< endl <<endl;
}
else
{
cout << "The angle you have entered is not acceptable" << endl;
return 0;
}
cout << "Enter the velocity in mph the rock is thrown: " << endl;
cin >> v;
if (v>=0 && v<=100)
{
cout << endl << "The velocity at which the rock is thrown is "<<v<<
" mph" << endl << endl;
}
else
{
cout << "The velocity you have entered is not acceptable" << endl;
return 0;
}
calcit (hite, angl, v);
}
int calcit (double hite, double angl, double v)
{
double tyme, dist;
v = v * (1609.344/3600);
angl = angl*(M_PI/180);
tyme = -v*sin(angl) + (sqrt((v*sin(angl)*v*sin(angl)) + 2*9.8*hite)/9.8) + (2*(v*sin(angl))/9.8);
dist = (tyme * v) * cos(angl);
cout << tyme << " " << dist <<endl;
}
I am trying to get the correct time the rock is traveling before it hits the ground but i keep getting incorrect answers. I am not sure if i am turning the equation to figure out the time the rock will be in the air until impact into c++ language right. any have any ideas??? i really need to finish this damn project.
Starting from the equation for the y (height above 0) for the rock we have
y = h + v*sin(a)*t - g/2*t^2
which transforms into
g/2 T^2 - v*sin(a)*T - h == 0
when we solve for the final condition y(T)=0.
This yields
T = v*sin(a)/g + sqrt(v*sin(a)*v*sin(a) + 2*g*h)/g
I just can't figure out where the first part -v*sin(angl) in your equation comes from. Everything else looks just fine. So it seems not to be with your code but with the equation you started.
The equation you want is:
s =ut + 1/2 at^2
s = Total distance traveled. (Height of the cliff)
u = Starting velocity (In your case negative as you are throwing
away from the target. And take into account
that not all the starting velocity is away
from the target (eg angle 0 mean u = 0))
a = acceleration (9.81 m/s2)
t = time (The value you want to calculate).
Rearrange the formula to solve for t
To find the solution for t where s = 0...
This formula is you basic quadratic:
y = a.x^2 + b.x + c
Where:
x/y are variables.
a/b/c are constants.
The solution for a quadratic equation where y is 0 is:
x = [ -b ± sqrt(b^2 - 4ac) ] / 2a
Notice the ± symbol. There are actually two solutions to the problem.
You should be able to deduce which one is correct for you as the other
is probably negative.
In your particular case the map is:
x ==> t
y ==> 0
a ==> 1/2.g
b ==> u
c ==> -s
I would suggest a few things to "clean up" the code a bit:
If functions return int ensure that they do really return something. (main doesn't have to but other functions do).
Calculate v * sin(ang1) once then use it in your formula thereafter. Not only more efficient but will make your code clearer.
Like you have given Pi a "constant", do that with other numbers you are using like 9.8 (gravitational force?)
If you have a confusing formula in the code, just introduce more variable names until the meaning becomes obvious. So long as you don't reassign different values to the same variables, this will not make the program confusing.
int calcit (double hite_meters, double angl_deg, double v_mph)
{
double const gravity = 9.8;
double v_ms = v_mph * (1609.344/3600);
double angl_rad = angl_deg * (M_PI/180);
double v_vertical = v_ms * sin( angl_rad );
double time_up = v_vertical / gravity; // [m/s] / [m/s^2] = [s]
double time_down_over_cliff = time_up;
// use quadratic formula t = ( -v - ( v^2 - 4gd )^1/2 ) / 2g:
double time_under_cliff = ( - v_vertical
- sqrt( ( v_vertical * v_vertical )
- ( 4 * - gravity * hite_meters ) ) // negative gravity = down
) / ( 2 * - gravity ); // ( [m/s] + ([m/s]^2 - [m/s^2]*[m])^1/2 ) / [m/s^2]
// = [m/s] / [m/s^2] = [s]
double time_total = time_up + time_down_over_cliff + time_under_cliff;
double v_horizontal = v_ms * cos( angl_rad );
double dist_horizontal = v_ms * time_total;
cout << time_total << " " << dist_horizontal <<endl;
}
Every line of code produces a new, relevant piece of information. When converting to a new unit, I introduce a new variable with a new name. Formulas involving more than one unit get the unit types explained in a comment. This should help turn up unit conversion errors which otherwise I can't help you catch.
Writing this kind of code involves more typing, but the time saved on head-scratching and asking for help more than makes up for it.
The program itself is not any less efficient. More importantly, it may be easily modified, so it won't turn into an inefficient mess after a few revisions.

Why is my code producing an output of nan? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My code is producing an output of nan.
I have looked around and I'm guessing it is as the equation is complicated from what I gather C++ doesn't recieve complicated equations too well.
But that doesnt seem right.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
int Backfill;
double SlopeAngleOfWall, AngleOfInternalFriction, AngleOfFrictionSoilAndWall, BackfillSlope, CoefficientOfActivePressure;
cout << "Retaining Wall Calculator \n";
cout << "Enter the slope angle of the wall, this is measured from the horizontal plane, therefor will be 90 degrees if the retaining wall is vertical \n";
cin >> SlopeAngleOfWall;
cout << "Enter the angle of internal friction \n";
cin >> AngleOfInternalFriction;
cout << "Enter the angle of friction between the soil and the wall \n";
cin >> AngleOfFrictionSoilAndWall;
cout << "Enter the angle of the backfill slope \n";
cin >> BackfillSlope;
/* To make sin function work is is typed (angle*pi/180) */
/* To make sin square work is is typesd (pow(sin (angle*pi/180), 2.0) */
/* To add a square root sqrt is used */
CoefficientOfActivePressure = (pow (sin ((SlopeAngleOfWall + AngleOfInternalFriction)*pi/180), 2.0)) / ((pow (sin (SlopeAngleOfWall*pi/180), 2.0) * sin ((SlopeAngleOfWall * AngleOfFrictionSoilAndWall) * pi / 180)) *( 1 + sqrt( ( sin ((AngleOfInternalFriction + AngleOfFrictionSoilAndWall) * pi / 180) * sin ( (AngleOfInternalFriction - BackfillSlope) * pi / 180) / sin ( (SlopeAngleOfWall - AngleOfFrictionSoilAndWall) * pi / 180 ) * sin ( (SlopeAngleOfWall + BackfillSlope) * pi / 180)))));
cout << "The coefficient of active pressure acting on the wall is" << CoefficientOfActivePressure <<"\n"
}
It looks like you are trying to implement Coulomb's Theory of Lateral earth pressure. The formula looks like this:
(From http://www.soilmanagementindia.com)
Assuming that your implementation is correct, the only way to get NaN as result is if the square-root argument is negative.
The bottom line is that the equation is not valid for all possible combinations of input, and for the wrong set of input an output of NaN is to be expected.