So I'm fairly new to programming and I'm just paying around trying to make some programs. This one is self-explanatory, but why do I get an invalid syntax for 'print' in line 12 (the first 'elif' statement)?
while True:
temp = raw_input("Would you like to convert:\nCelsius to Fahrenheit (press 1)\nor\nFahrenheit to Celsius (press 2)\n")
if temp == 1:
celsius = raw_input("What is the temperature in degrees Celsius?")
tempFahr = ((int(celsius)*(9/5))+32)
print "When it is " + celsius + " degrees celsius, it is " + tempFahr + "degrees fahrenheit."
elif temp == 2:
fahrenheit = raw_input("What is the temperature in degrees Fahrenheit?")
tempCel = ((int(fahrenheit)-32)*(5/9)
print "When it is " + fahrenheit + " degrees fahrenheit, it is " + tempCel + "degress celsius."
elif temp = 42:
print "You're a winner!"
else:
print "That is not a valid option."
print "Press 'enter' to input another value"
raw_input()
Also, if I over complicated something, I would really appreciate if you could point out what it was. Try not to correct me too much, though, I would like to try and figure it out on my own.
There are two syntax errors. First, you forgot a closing ) in the tempCel line, which confuses Python about the next print:
tempCel = ((int(fahrenheit)-32)*(5/9)
print "When it is " + fahrenheit + " degrees fahrenheit, it is " + tempCel + "degress celsius."
Then you used = where you meant ==:
elif temp = 42:
There are other errors -- for example, you're comparing temp, which is a string, to 1 and 2, which are integers, and you also might want to type 5/9 at the console to see what it gives you -- but they're not SyntaxErrors.
you should try
print("When it is " + str(fahrenheit) + " degrees fahrenheit, it is " + str(tempCel) + " degress celsius.")
Related
Input prompt asks for a starting time, and then a duration time where it returns two times: one time where they are added, and one where they are subtracted. I've gotten the basics of them, but when I try and do it for certain times (ex: 1:18 and 10:39) I get a negative error:
X Input of 1:18 10:39 : expected [11:57, 2:39] but found [11:57, -9:-21]
Here's the code that does the calculations:
int timeHours, timeMinutes, durHours, durMinutes;
cout << " Time: ";
cin >> timeHours;
cin.get();
cin >> timeMinutes;
cout << " Duration: ";
cin >> durHours;
cin.get();
cin >> durMinutes;
int time, duration, after, before, afterHours, afterMinutes, beforeHours, beforeMinutes;
const int MINUTES_IN_DAY = 60 * 24;
time = (timeHours * 60) + timeMinutes;
duration = (durHours * 60) + durMinutes;
after = time + duration;
before = time - duration;
afterHours = after / 60 % 12;
afterMinutes = after % 60;
beforeHours = before / 60;
beforeMinutes = before % 60;
cout << endl;
cout << durHours << ":" << setfill('0') << setw(2) << durMinutes << " hours after, and before, "
<< timeHours << ":" << timeMinutes << " is [" << afterHours << ":" << setw(2) << afterMinutes << ", "
<< beforeHours << ":" << setw(2) << beforeMinutes << "]" << endl;
The failed test above shows that the sum (1:18 + 10:39) works but the difference (1:18 - 10:39) does not work. It gives me "-9:-21" which should be able to be fixed by adding 24 hours, which is even what my assignment suggests: "This is easily done by adding a day (or two or three) to before when calculating the difference" but when I add 1440 (60 * 24) to the "before" initialization:
before = (time - duration) + MINUTES_IN_DAY;
and convert back from minutes to normal time I get 14:39, which is 2:39, but in 24 hour form, not 12 (incidentally it also makes all the other tests which were passing now failing). I think there's some hint when it says "by adding a day (or two or three) since obviously 1440 is different from 1440*2 or *3, but I'm not seeing it and I have to be missing something obvious. I know I'll have to fix it for midnight as well but I'll change that later. If anyone knows what I'm trying to explain, I'd really appreciate it
Usually, when working with times/dates it's easier to make yourself a function to convert a human-readable date to milliseconds or seconds (and vice versa) and build up from that base. In your case, you'll just add/subtract the two time-marks in seconds for example:
long long time = toSec(timeHours, timeMinutes, timeSeconds);
long long duration = toSec(durHours, durMinutes, durSeconds);
string after = toDate(time + duration);//somethig like 12:34:00 (hh:mm:ss)
string before = toDate(time - duration);
however, putting effort in making such conversion functions would be an overcomplication if all you use them for is a one-time calculation.
( like you suggested to add MINUTES_IN_DAY) to solve the negative values problem you can use the %MINUTES_IN_DAY to avoid the overflow caused by adding MINUTES_IN_DAY to a positive value
before = ((time - duration)+MINUTES_IN_DAY)%MINUTES_IN_DAY;
just finished my first week of C++(using Visual Studio 2017), I wrote a program that asks the user for the amount of money and will print the number of bills and coins. it works at the beginning, but sometimes it just prints wrong number.(when the user input $1.28, it shows 1 dollar, 1 quarter and 2 pennies.)
here is my code, is there anything wrong? the algorithm or the data type?
#include<iostream>
using namespace std;
float Q = 0.25;
float D = 0.10;
float N = 0.05;
float P = 0.01;
float Dollar = 1;
float money;
float dollars, quarters, dimes, nickels, pennies;
int main() //to break money into coins.
{
cout << "how many money do u have?" << endl;
cin >> money;
dollars = (int)money;
quarters = (int)((money - dollars*Dollar)/Q);
dimes = (int)((money - dollars*Dollar - quarters*Q) / D);
nickels = (int)((money - dollars*Dollar - quarters*Q - dimes*D) / N);
pennies = (int)((money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) / P);
cout << "$" << money << " can be break into :" << endl;
cout << dollars << " dollars. " << endl;
cout << quarters << " quarters. " << endl;
cout << dimes << " dimes. " << endl;
cout << nickels << " nickels. " << endl;
cout << pennies << " pennies. " << endl;
}
how to avoid the loss of precision when trying to round number? (C++)
When you convert from floating point to integer, the fractional part is truncated. To ensure no loss of integer precision (getting the right "whole"), add 0.5 to the result each time e.g:
quarters = static_cast<int>(((money - dollars*Dollar)/Q)+0.5);
This however doesn't work when the result is negative e.g:
50.5 - 100 = -49.5 -> +1 = -48.5 -> -48... not 49
For negatives you would want to therefore subtract 0.5.
I'd assume, that in the line
pennies = (int)((money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) / P);
the part (money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) will produce a value, that is not exactly .03, but a tad below. This is due to the nature of floating point arithmetic, you should read on that. Given that it's something like .029999999995, division by .01 will not yield 3.0, but maybe 2.9999999995. Since you are not rounding, but casting the value to an integer, the whole part after the period will be thrown away, hence it results in 2 pennies.
How can you solve this issue?
The simplest thing will be to round the value instead of casting it, this should yield the correct value, but this is kind of a hacky solution to an issue there is an exact solution for. You could also try to use double instead of a float, but this, too, would not solve the issue. You might get this correct, but the same a similar bug could still occur.
Store whole pennies
You could store the whole amount as an integer (whole pennies)
int amountInPennies;
int penniesPerDollar = 100;
int penniesPerQuarter = 25;
int penniesPerDime = 10;
int penniesPerNickle = 5;
int totalDollars = amountPennies / penniesPerDollar;
int totalQuarters = (amountPennies - totalDollars * penniesPerDollar) / penniesPerQuarter;
...
Decimal types
In a real world application dealing with money (well, depending on the type) you'd most likely go with some kind of decimal type instead of a float. According to this answer there are libraries with arbitrary precisions arithmetic available under the GNU license. You could still roll your own decimal type, that - more or less - does what I presented in the first approach. This might be a great excercise to learn, but maybe a ready-made library would be the better option when it comes to a real world application.
if I try to type in the "oz" or "OZ" the else if statement doesnt seem to proceed and I do not know why. Any help would be appreciated! THANKS!!!
Scanner input = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
String Ma = "mass" + "MASS";
String La = "oz" + "OZ";
System.out.println("Hi, what are you trying to find?");
System.out.println("mass");
System.out.println("vol");
System.out.println("temp");
System.out.println("sphere");
System.out.println("density");
String convert = input.nextLine();
if (Ma.contains(sb.append(convert))) {
System.out.println("You are trying to convert mass.");
System.out.println("Type the unit of measurement you are trying to convert to.");
System.out.println("If you are trying to find mass type mass.");
System.out.println("pound");
System.out.println("ounce");
System.out.println("ton");
System.out.println("gram");
System.out.println("mass");
String mass = input.nextLine();
}
else if (La.contains(sb.append(convert))) {
System.out.println("34223412351Type the number of oz.");
double oz = input.nextDouble();
System.out.println(oz + " oz equal to " + oz / 16 + " lb.");
System.out.println(oz + " oz equal to " + oz / 32000 + " ton.");
System.out.println(oz + " oz equal to " + oz * 0.02835 + " kg.");
System.out.println(oz + " oz equal to " + oz * 28.35 + " g.");
System.out.println(oz + " oz equal to " + oz * 2835 + " cg.");
System.out.println(oz + " oz equal to " + oz * 28350 + " mg.");
}
}
}
Why do you need the stringbuilder you can directly use Ma.contains(convert) and La.contains(convert), this will run the if else properly.
The reason it's not running for oz in your case is that the string builder is appending 'oz' twice.
1. When it checks to see in Ma
2. When it checks to see in La
So at La your sb contains 'ozoz', which is why the else if is never run.
If you need to use the stringbuilder here use sb.append after reading the string from scanner and not in the if conditions
I am trying to code a guessing game in JES using the pseudo code below:
Generate a random single digit number
Have the user guess the number
If the user does not guess correctly give them a clue – indicate whether the number is even or odd and ask the user to guess again.
If the user does not guess correctly, give another clue – indicate whether the number is a multiple of 3 and ask the user to guess again.
If the user does not guess correctly, give another clue – indicate whether the number is less than or greater than 5 and ask the user to guess again.
If the user does not guess correctly,
display a box indicating the correct answer and the number of guesses the user made.
If the user has guessed correctly, display a box indicating their guess is correct and how many guesses were required
Show the amount of time the user played the guessing game.
There are so many conditions I have no clue how to have the program ask each question, analyze the answer, and if the condition isn't met, to move on to the next one. When I run this code, it is just stuck in the loop of asking the user to guess and does not move through the if statements to give the user hints if they are incorrect.
Below is my current code which obviously is incorrect. I am also aware there may be indenting issues in this post.
from random import *
from time import *
def main():
a= randrange( 0, 11 )
start= clock()
numberOfGuesses= 0
userGuess= requestInteger( " Please guess a single digit number " )
while userGuess != a:
userGuess= requestInteger( " Please guess a single digit number " )
if userGuess % 2 == 0:
showInformation( " Incorrect! Please try again. Hint: The number is even " )
if userGuess % 2 != 0:
showInformation( " Incorrect! Please try again. Hint: The number is odd " )
if userGuess % 3 != 0:
showInformation( " Incorrect! Please try again. Hint: The number is not a multiple of 3 " )
if userGuess > 5:
showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
if userGuess < 5:
showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
else:
showInformation( " Correct " )
REVISED AND WORKING CODE
from random import*
from time import*
def main ():
a= randrange( 0, 10 )
start= clock()
numberOfGuesses= 0
userGuess= requestNumber( " Please guess a single digit number " )
end= clock()
elapsedTime= end - start
if userGuess != a and userGuess % 2 == 0:
showInformation( " Incorrect! Please try again. Hint: The number is even " )
userGuess= requestNumber( " Please guess a single digit number " )
numberOfGuesses= numberOfGuesses + 1
elif userGuess != a and a % 2 != 0:
showInformation( " Incorrect! Please try again. Hint: The number is odd " )
userGuess= requestNumber( " Please guess a single digit number " )
numberOfGuesses= numberOfGuesses + 1
if userGuess != a and a % 3 != 0:
showInformation( " Incorrect! Please try again. Hint: The number IS NOT a multiple of 3 " )
userGuess= requestNumber( " Please guess a single digit number " )
numberOfGuesses= numberOfGuesses + 1
if userGuess != a and a > 5:
showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " )
userGuess= requestNumber( " Please guess a single digit number " )
numberOfGuesses= numberOfGuesses + 1
if userGuess != a and a < 5:
showInformation( " Incorrect! Please try again. Hint: The number is less than 5 " )
userGuess= requestNumber( " Please guess a single digit number " )
numberOfGuesses= numberOfGuesses + 1
if userGuess == a:
showInformation( " Correct! " )
showInformation( " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " )
elif userGuess != a :
showInformation( " Incorrect! " + " " + " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " )
its stuck in the loop because user cant guess the same num that randnum genertes
"while userguess !=a " it'll never be true
I've looked at similar questions, but being a total newbie at this, they haven't helped much, when I try to run my final if statement I run into this error, how can I make my cout statement clearer? Its intended purpose is to output how many bags of garbage it can accept, how many the user is trying to give it, and how many bags will be left over if it cannot take them all.
while(( reg < 50) && (met< 20) && (glass < 20))
{
reg=reg+reg; met=met+met; glass=glass+glass;
cout<< " I have enough "<< endl;
if(reg+=reg > 50){
cout<< "I can only accept " << 50 - (reg+=reg) << "of your " << (reg+=reg)<<" regular bags of garbage, I'll leave the other " << 50 - (reg+= reg)<< " I'll leave the other " << reg- (50 - reg+=reg)<< endl;
}
50 - reg += reg;
operator+= has lower precedence than operator-. The above statement is interpreted as:
(50 - reg) += reg;
which won't work. You probably wanted:
50 - (reg += reg);