How to split a float into two variables? (c++) - visual-c++

I can't figure out how to take the total number of hours and split it into regular hours and overtime hours.
What I would like to achieve is to: add a module that splits the number of hours worked into regular hours and overtime hours. This module must have one ‘in’ parameter and two ‘out’ parameters.
What I could come up with was:
if (total_hours >= 0 || total_hours <= 40) {
reg_hours = total_hours;
}
if (total_hours >= 41 || total_hours <= 60) {
ovt_hours = (total_hours - 40);
}
total_hours is my input. And reg_hours and ovt_hours are my outputs. If I put in 35.6 for total_hours, it'll compile and give me -4.40. It does fine with an input of 40 or higher, but when it comes to anything less than that it always produces a negative ovt_hours value. I'm really confused on how to stop it from giving me a negative number. I've been searching everywhere to find a solution, but I couldn't find anything that could help me understand what I am doing wrong. It would help me greatly if anyone could explain this in the simplest way possible.

You can work up to 40 regular hours...
int reg_hours = max(total_hours, 40);
If you've worked more than 40 hours, then any extra hours are overtime hours...
int ovt_hours = 0;
if (total_hours > 40) {
ovt_hours = total_hours - 40;
}

There is one thing you should understand:
Using "if" statement with another "if" statement (without "else if" or "else") would definitely make your compiler go to both "if" statements (assuming the conditions are true).
Also, you should notice that in your code there is a logic mistake:
"if (total_hours >= 0 || total_hours <= 40)"
"if (total_hours >= 41 || total_hours <= 60)"
When you input "total_hours=35.6", the compiler with go into both if statements. Why? Because 35.6 is >= 0 and <= 40 (1st if statement) and 35.6 is <= 60 (2nd if statement).
Therefore you MUST use "else if" for your 2nd if statement.
Another thing is that, you might need to consider to use "&&" instead of "||" since you are checking a range between 2 values. Using "||" means you are only checking a range lower/higher than a value.

Related

Python Logical Operators find the right way if(and and or or)

Can not find the mistake in logical operators, may be someone can give me a hint how to put AND OR OR.
Problem is with if data and data and data and (or or or)
in () > I need to accept code:
contains capital letters, then the number of capitals must be odd
have at least 4 letters (independent of case)
so it means: UPPER + LOWER >= 4 or UPPER >= 4 or LOWER >= 4
output should be:
checker_code("Dfgh#88$")
True
def checker_code(security_code):
data = {'upper':0, 'lower':0, 'spec':0, 'digit':0, 'sum':0}
spec_charact = ['!','#','#','$','%','^','&','*','(',')','?',',','.']
if len(security_code) < 8 or len(security_code) > 30:
return False
for i in security_code:
if any(i.isupper() for i in security_code):
data['upper'] = data['upper'] + 1
if i.islower():
data['lower'] = data['lower'] + 1
if i in spec_charact:
data['spec'] = data['spec'] + 1
if i.isdigit():
data['digit'] = data['digit'] + 1
if i.isdigit():
data['sum'] = data['sum'] + int(i)
if(data['upper'] % 2 !=0 and data['spec'] >= 2 and data['digit'] >= 2 and data['sum'] % 2 == 0 and (data['upper'] + data['lower'] >= 4 or data['upper'] >= 4 or case['lower'] >= 4)):
return True
else:
return False
Change your line
if any(i.isupper() for i in security_code):
to this:
if i.isupper():
Since you are already iterating for i in security_code in your outer for loop, it is redundant to do it again in your first if-statement. I think your code is applying whether the 1st character is upper across all letters, so it thinks your string of 8 characters has 8 upper-case characters since "D" is uppercase
Your test if any(i.isupper() for i in security_code): is adding to data["upper"] everytime through the loop because you are checking all of security_code at every iteration and since it does have a uppercase letter, it adds to the count.
Instead, just do if i.issuper(): to only check the current element of the security code.

How do I achieve this following function only using while loop?

I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response

Can you combine a while statement and an If statement together into one line?

I am creating a game where it plays to 10 points to win and you can also win if a player reaches 7 points without the other player receiving any.
I have an if statement inside a while statement and was wondering if there was a way to combine them into one general statement.
I have tried combining them with an extra set of parenthesis on for the if portion as well as tried to change up the and/or boolean values to see if I got those wrong.
while (count1 <= 10 and count2 <= 10):
if (count1 == 7 and count2 == 0) or (count2 == 7 and count1 == 0):
Happy Path: The while and if loops combine into one statement, while still keeping the rules stated in the summary.
Currently: I have tried a bunch of combinations but they all go to an else statement or go beyond the 10 point limit, which tells me that the while parameters are wrong.
Try:
while (count1 <= 10 and count2 <= 10) or ((count1 != 7 or count2 != 0) and (count2 != 7 or count1 != 0)):
I'm using following logic laws in here:
not (a or b) <=> not a and not b
and
not (a and b) <=> not a or not b

Making a variable a 'less than' value?

i'm really new to Python and am completely stuck
is there any way to make the less than value a variable
for example
x = int(input ("Input a value for x: "))
i = 1
while i < x:
x += i
i += 1
else:
print ("here is your new number:", x,)
whenever i use this, nothing happens
thanks for your help
It's not technically true to say that nothing happens, plenty is happening.
However, one thing that's not happening is the thing that generates the output (unless you enter a value less than or equal to one).
The while..else construct will only execute the else block if the while block did not do any iterations.
So, if you want output after the loop regardless of whether the loop body executes, get rid of the else and unindent the print.
The other thing that's not happening is the exit condition of the loop itself. If i starts out less than x (and they're both positive to start with), adding i to x then adding 1 to i will never give you a situation where i is not less than x.
Think about (for example):
x i Description
----- ----- -----------
3 1 Initial state
4 2 x += i; i += 1;
6 3 x += i; i += 1;
9 4 x += i; i += 1;
13 5 x += i; i += 1;
18 6 x += i; i += 1;
24 7 x += i; i += 1;
31 8 x += i; i += 1;
You can see that x is increasing at a faster rate than i, hence i < x will always be true.
How you fix that depends entirely on what you're trying to achieve. Since you have described your problem in terms of the code, your code matches perfectly your requirements. Hence, since you state it's not working as you expected, it appears your requirements may need some work :-)
I would suggest stating, in English, what you're trying to achieve here, and we can then suggest where your implementation has gone wrong.
What you wrote will result in an infinite loop if i < x in the beginning. So it will never reach the print statement that you hope it will. Plus, I also believe that you have to delete the else and indent the print statement.

How to create function that returns 'change in highest denominations'

I am trying to make a programme that will return the correct change, in the highest denominations possible
i.e $73 will return 1 x $50, 1 x $20, 1 x $2 and 1 $1
(I am using whole values of $100, $50, $20, $10, $5, $2, $1)
I have a long code that works...it is
hundred = x // 100
hundred_remainder = x % 100
fifty = hundred_remainder // 50
fifty_remainder = hundred_remainder % 50
twenty = fifty_remainder // 20
etc....then
if hundred > 0:
print (str(hundred) + " x $100")
if fifty> 0:
print (str(fifty) + " x $50")
etc....which works fine, but I know there must be a way of writing a function that has a loop to work it out with less typing. Something like X = $345, then it gets 3 x $100, subtracts that from the total and updates X with the remainder, then repeats the process going through each denomination, until complete. I'm just a bit unsure how to figure it out, any guidance will be greatly appreciated!
I think a cool model for this problem is defining the values that you consider "legal" up-front, and then iterating over those from the top to the bottom to reach your counts. Consider the following loop:
#where x is the value from which you're making change
legal = [100,50,20,10,5,2,1,.50,.25,.10,.05,.01]
for dolAmount in legal:
count = x//dolAmount
if count > 0:
print int(count),\
dolAmount,\
" coin(s)" if dolAmount<1 else " dollar bill(s)"
x-=count*dolAmount
# prints lines like this for x=103.58:
#
# 1 100 dollar bill(s)
# 3 1 dollars bill(s)
# 1 0.5 coin(s)
# 1 0.05 coim(s)
# 3 0.01 coin(s)
# ehhh actually it will probably say 2 0.01 coin(s) because floating points....
The formatting needs work (what the heck is a 0.5 coin?), but this is a neat way of saving yourself a lot of code-writing, and the pattern is applicable to other programming endeavors. In general, when you find yourself creating a lot of variables/constants by hand, it's probably time to start thinking about a list (or similar collection)!
Check out http://www.codeskulptor.org/#user39_ur6ybhs9HAmknOL.py for a learning-example of what this would look like in practice (used within a function!) Happy coding!
I did something similar in C a few weeks ago; I do not know Python well, so Im just going to write the logic of the function. Im sure you will be able to translate it flawlessly to Python ;)
We know that the highest bill is that of $100;
So, say we have an ammount of $335.
What we should do first is create an int variable for each Bill denomination.
int b100 = 0;
int b50 = 0;
int b20 = 0;
int b10 = 0;
int b5 = 0;
int b2 = 0;
int b1 = 0;
Then, we should make a while loop:
while(ammount >= 100){
ammount = ammount - 100;
b100++;
}
here what we did is obtain the total ammount of $100 bills that we'll need.
After this while loop ammount must be equals to 35, and b100 should have a value of 3;
then we repeat the code with the next bill:
while(ammount >= 50){
ammount = ammount - 50;
b50++;
}
In this case, as ammount has a value of 35, and it's lower that 50, it won't enter the while loop; instead it will pass to the next one:
while(ammount >= 20){
ammount = ammount - 20;
b20++;
}
Etc....
After all those whiles we should have ammount with a value of '0';
And the bills variables with the quantity of bills required.
In the example of $335 the variables value should be like this:
$100 bills --> 3 $20 bills --> 1 $10 bills --> 1 $5 bills --> 1
Hope it helped, any doubts feel free to ask ;)

Resources