How do I go about getting the real result for 50%60 in C++ - c++

I please check this problem I'm creating a Time Base app but I'm having problem getting to work around the modulus oper (%) I want the remainder of 50%60 which I'm expecting to output 10 but it just give me the Lhvalues instead i.e 50. How do I go about it.
Here is a part review of the code.
void setM(int m){
if ((m+min)>59){
hour+=((min+m)/60);
min=0;
min=(min+m)%60;
}
else min+=m;
}
In the code m is passed in as 50 and min is passed in as 10
How do I get the output to be 10 for min in this equation min=(min+m)%60; without reversing the equation i.e
60%(min+m)

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined).
you should do : 60 % 50 if you want to divide by 50
Or, if you want to get mins, i think you don't need to make min=0.

When you do 50 % 60, you get a remiainder of 50 since 50 cannot be divided by 60.
To get around this error, you can try doing do something like 70 % 60 to get the correct value as a result, since you do not want to use 60 % 50
This would follow the following logic:
Find the difference between 60 and min + m after min is set to zero if min + mis less than 60. Store it in a variable var initially set to zero.
check if the result is negative; if it is, then set it to positive by multiplying it by -1
When you do the operation, do min = ((min + m) + var) % 60; instead.
***Note: As I am unfamiliar with a Time Base App and what its purpose is, this solution may or may not be required, hence please inform me in the comments before downvoting if I there is anything wrong with my answer. Thanks!

It looks like you are trying to convert an integral number of minutes to an hour/minute pair. That would look more like this instead:
void setM(int m)
{
hour = m / 60;
min = m % 60;
}
If you are trying to add an integral number of minutes to an existing hour/minute pair, it would look more like this:
void addM(int m)
{
int value = (hour * 60) + min;
value += m;
hour = value / 60;
min = value % 60;
}
Or
void addM(int m)
{
setM(((hour * 60) + min) + m);
}

Related

Best way to find difference between two values in a cyclic system?

Take for example time: if we have the starting hour and ending hour, what's the best way to find the number of hours between them?
If we take a 12-hour clock, we'd get the following results
from 1 to 5 = 4
from 11 to 1 = 2
What is the most efficient way to do that?
Assuming a 12 hour clock, the number of hours from a to b can be calculated as:
difference = ((b + 12) - a) % 12;
This also assumes that a and b are both in the range [1, 12]. In case they are not, you can do:
a %= 12;
b %= 12;
before doing the difference calculation.
Assuming input already in range 1-12, you might do
return b - a + (b < a) * 12;
benchmark showing a 2 times performance gain over cigien's solution.

if statement inside of for loop not being executed

Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex:
#include <iostream>
int reverseNumber(int testNum)
{
int reversedNum, remainder = 0;
int temp = testNum;
while(temp != 0)
{
remainder = temp % 10;
reversedNum = reversedNum * 10 + remainder;
temp /= 10;
}
return reversedNum;
}
int main()
{
const int MIN = 100;
int numOne = 99;
int product = 0;
for(int numTwo = 10; numTwo < 100; numTwo++)
{
product = numOne * numTwo;
if (reverseNumber(product) == product)
{
int solution = product;
std::cout << solution << '\n';
return 0;
}
}
return 0;
}
My main thought process behind this is that the for loop will go through every number from 10 to 99 and multiply it by 99. My intended outcome is for it to print 9009 which is the largest palindrome with 2 factors of 2 digits. So what I think should happen here is the for loop will go from 10 to 99, and each loop it should go through the parameters of the if statement which reverses the number and sees if it equals itself.
I've made sure it wasn't a compiler issue, as this is recurring between different compilers. The reverseNumber() function returns the proper number every time I've tested it, so that shouldn't be the problem, however this problem only occurs when the function is involved in the logical comparison. By this I mean if that even I set it equal to a variable and put the variable in the if parameters, the issue still occurs. I'm pretty much stumped. I just hope it's not some silly mistake as I've been on this for a couple days now.
int reversedNum, remainder = 0;
You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule.
In other words, it should probably be:
int reversedNum = 0, remainder;
or even:
int reversedNum = 0;
int remainder;
One other thing that often helps out is to limit the scope of variable to as small an area as possible, only bringing them into existence when needed. An example of that would be:
int reverseNumber(int testNum) {
int reversedNum = 0;
while (testNum != 0) {
int remainder = testNum % 10;
reversedNum = reversedNum * 10 + remainder;
testNum /= 10;
}
return reversedNum;
}
In fact, I'd probably go further and eliminate remainder altogether since you only use it once:
reversedNum = reversedNum * 10 + testNum % 10;
You'll notice I've gotten rid of temp there as well. There's little to gain by putting testNum into a temporary variable since it's already a copy of the original (as it was passed in by value).
And one other note, more to do with the problem rather than the code. You seem to be assuming that there is a palindrome formed that is a multiple of 99. That may be the case but a cautious programmer wouldn't rely on it - if you're allowed to assume things like that, you could just replace your entire program with:
print 9009
Hence you should probably check all possibilities.
You also get the first one you find which is not necessarily the highest one (for example, let's assume that 99 * 17 and 99 * 29 are both palindromic - you don't want the first one.
And, since you're checking all possibilities, you probably don't want to stop at the first one, even if the nested loops are decrementing instead of incrementing. That's because, if 99 * 3 and 97 * 97 are both palindromic, you want the highest, not the first.
So a better approach may be to start high and do an exhaustive search, while also ensuring you ignore the palindrome check of candidates that are smaller that your current maximum, something like (pseudo-code)
# Current highest palindrome.
high = -1
# Check in reverse order, to quickly get a relatively high one.
for num1 in 99 .. 0 inclusive:
# Only need to check num2 values <= num1: if there was a
# better palindrome at (num2 * num1), we would have
# already found in with (num1 * num2).
for num2 in num1 .. 0 inclusive:
mult = num1 * num2
# Don't waste time doing palindrome check if it's
# not greater than current maximum - we can't use
# it then anyway. Also, if we find one, it's the
# highest possible for THIS num1 value (since num2
# is decreasing), so we can exit the num2 loop
# right away.
if mult > high:
if mult == reversed(mult):
high = mult
break
if high >= 0:
print "Solution is ", high
else:
print "No solution"
In addition to properly initializing your variables, if you want the largest palindrome, you should switch the direction of your for loop -- like:
for(int numTwo = 100; numTwo > 10; numTwo--) {
...
}
or else you are just printing the first palindrome within your specified range

/= operation in C++

As I understand this code returns the number of digits entered in the function but I don't understand this operation:
(number /= 10) != 0 at all..I understand that this line
number /= 10
equal to number = number / 10 but why not but why in this function they don't write number / 10 != 0? and what are the differences?
std::size_t numDigits(int number) // function definition.
{ // (This function returns
std::size_t digitsSoFar = 1; // the number of digits
// in its parameter.)
while ((number /= 10) != 0) ++digitsSoFar;
return digitsSoFar;
}
(number /= 10) != 0
This actually has 3 steps. It...
Calculates number / 10
Assigns that value to number
Checks if that value is not equal to 0
So in answer to your question, "why in this function they don't write number / 10 != 0," let's walk through what that does:
Calculates number / 10
Checks if that value is not equal to 0
Can you see the difference between the two?
If you're still not sure why this matters, put an output statement in the while loop that'll show number and digitsSoFar and try to run that function both the way it's written and then with your proposed version.

Why do these functions give the correct output 75% of the time?

(this function is part of a larger program but operates independently of other functions.)
Ok I have a function jacket and given 3 inputs it produces the correct output only 75% of the time.
I do not know the inputs but I know the output is wrong.
I do not know what is wrong and have no idea how to fix it.
I assume it is the same 12 values entered each time the function is submitted to myProgrammingLab.
So it may be a problem with a specific input.
Thanks.
The Description:
Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over age 30. (note that the adjustment only takes place after a full 10 years. So, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
edit: changing tmp to float still produced the error.
float jacket(float weight, float height, int age) {
double result = (height * weight) / 288;
/*now for every 10 years past 30 add (1/8) to the result*/
if((age - 30) > 0){
int temp = (age - 30) / 10;
result = result + (temp * .125);
}
return result;
}
This is the same function written differently with the same problem.
float jacket(double jWeight, double jHeight, int jAge)
{
double jSize = ((jWeight*jHeight)/288.0);
int i = jAge/10 - 3;
if((jAge/10)>3)
jSize += 0.125*i;
return jSize;
}
This is a third function with the same problem
float jacket(double weight, double height, int age)
// calculates the jacket size, adjusting for age in increments
// of ten years, if customer is over 30 years of age.
{
int age_factor;
double j_size;
j_size = (height*weight)/288.0;
if (age >=30)
{
age_factor = (age-30)/10; //note possible truncation.
j_size += age_factor/8.0;
}
return j_size;
}
The first time the function is called it produces an incorrect return value. the remain 3 times it is called the return value is correct.
Observe:
Expected Output:
jacket·size·=·24.17↵
jacket·size·=·40.00↵
jacket·size·=·46.04↵
jacket·size·=·35.42↵
Actual Output:
jacket·size·=·24.29↵
jacket·size·=·40.00↵
jacket·size·=·46.04↵
jacket·size·=·35.42↵
*All three functions given the same input produce the same output
int temp = (age - 30) / 10;
By making temp an int, you will get incorrect results, because of truncation. Try using a float instead.
I guess one could say that 31 isn't necessarily 1 year over 30. Try int temp = (age - 31)/10;. Personally I think that's wrong, as does everyone else here, but someone could argue that the moment one turns 31 one is only a few seconds over 30. It's worth a try, anyway.

For Loops for a Time Class

I am trying to write a for loop for a time class. Where if the minutes entered are over 60, 60 is subtracted from the total minutes and hours is incremented by 1 until the final minutes left is less than 60 . I was doing if statements like
if (m > 59){
m = m - 60;
h++;
if (m > 59)... etc..
but that doesn't cover every case and I feel like I should know how to do this for loop but I can't figure it out. Any help would be appreciated, thanks
Well if it doesn't have to be implemented using loops, you could do simply
h = m / 60;
m = m % 60;
It is the fastest and cleanest way to do that, I suppose.
Not really sure whether you want to do anything else inside the loops. If so, this won't help you very much.
Edit:
Here is some explanation of how it works.
What m / 60 does is called integer division. It returns floor of the expression. So for example if m = 131 than m / 60 = 2.
The second expression uses the modulo operator. Basically it finds the reminder after division. Back to our example, m % 60 = 11 since m can be written as m = 60 * 2 + 11 = 131. For further information please refer to wiki.
#Jendas has a good simple answer to the overall problem, but if you want to keep with this format but fix your issue with loops, you could put the whole thing in a while loop instead of individual if statements:
while(m >59)
{
m = m - 60;
h++;
// do anything else you need to take care of
}
// finishing statements
h = 0;
while (m >= 60)
{
m = m - 60;
h++;
}
You probably want to use >= 60 instead of 59.
Also, as Jendas rightly suggested you might want to research a little about the modulus operator '%'