I cannot seem to append my else if statement - if-statement

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

Related

C++ - Where in my code should I include static_cast?

My static_cast does not seem to be working. I create 5 int variables at the beginning of my code and attempt to change one (the total) to a double after performing calculations on the other 4, but it keeps displaying the int.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main ()
{
int grade1, grade2, grade3, grade4, avg;
cout << "Please input four grades: " << endl;
cin >> grade1;
cin >> grade2;
cin >> grade3;
cin >> grade4;
avg = (grade1 + grade2 + grade3 + grade4) / 4;
cout << "Grades: " << grade1 << ", " << grade2 << ", " << grade3 << ", " << grade4 << endl;
cout << "\n";
cout << "Average grade: " << static_cast<double>(avg) << endl;
return 0;
}
When you are combining the integers and assigning them to avg.
You already have integer rounding conversion, so you need to static cast before you assign the number to the avg result.
You also don't even need to use static cast as long as you divide by 4.0 and make avg a double.
Example:
double avg = static_cast<double>(grade1+grade2+grade3+grade4) / 4.0;
// Alternative without static that still works
double avg = (grade1+grade2+grade3+grade4) / 4.0;
I would suggest that the literal answer to your question "Where in my code should I include static_cast?" is quite simple: nowhere, if at all possible.
static_cast - like all the C++ _cast operators, and all explicit (C-style) typecasts should be avoided wherever possible. They have their uses, but it is better to minimise their usage, and certainly to avoid using them as blunt instruments to fix problems in code.
In your case, the correct results can be obtained quite simply by using appropriate types of variables, and any literal values having a suitable type.
Firstly, avg needs to be of type double. This involves changing
int grade1, grade2, grade3, grade4, avg;
to
int grade1, grade2, grade3, grade4;
double avg;
Second, the calculation of the value of avg needs to be changed so it doesn't do an integer division. This means changing
avg = (grade1 + grade2 + grade3 + grade4) / 4;
(which doesn't work because grade1, ... grade4 are all of type int, their sum is an int, the literal 4 is an int, and dividing two ints produces an int) to
avg = (grade1 + grade2 + grade3 + grade4) / 4.0; // note the 4.0
This works, because the literal 4.0 has type double. The value (grade1 + grade2 + grade3 + grade4) is calculated as an int but, because it is being divided by a double, that integral value is converted implicitly to double before performing the division - and the result is of type double.
This is the only place in which I would consider using a static_cast here, by converting the 4 to a double.
avg = (grade1 + grade2 + grade3 + grade4) / static_cast<double>(4);
which has the same net effect as the previous calculation of avg. In your code, it makes little difference. But a static_cast can be useful here in more general-purpose code, for example, if the number of input values (grade1, grade2, etc) is calculated as an integral value (e.g. the number of elements in an array).
The third thing you can do is remove the static_cast from the statement that outputs avg since it is now redundant (converting a double to double has no effect). In other words turn
cout << "Average grade: " << static_cast<double>(avg) << endl;
to
cout << "Average grade: " << avg << endl;
There are two issues in your code.
The first is that you declared avg as int, so the result is going to be rounded as int always.
However, declaring avg as double will not solve your problem immediately. In C++, operators are executed on objects of the same type and the result is an object of the same type.
(grade1 + grade2 + grade3 + grade4) is an int and 4 is an int, therefore the result will be an int. It doesn't matter if later is implicitly or explicitly casted to double, you will still get a rounded result.
In case the operands are not the same type, the compiler will implicitly promote one to match the other. The following lines will give you the correct result:
static_cast<double>(grade1 + grade2 + grade3 + grade4) / 4;
(grade1 + grade2 + grade3 + grade4) / 4.0;
static_cast<double>(grade1 + grade2 + grade3 + grade4) / 4.0;
An int cannot hold decimal places. int / results in an int, there are no decimals that result. You need to use the correct /, i.e at least one of the operands must be double to get a double result.
#include <iostream>
int main () {
std::cout<<"Please input four grades: "<<std::endl;
int grade1, grade2, grade3, grade4;
std::cin>>grade1;
std::cin>>grade2;
std::cin>>grade3;
std::cin>>grade4;
double avg=static_cast<double>(grade1+grade2+grade3+grade4)/4;
std::cout<<"Grades: "<<grade1<<", "<<grade2<<", "<<grade3<<", "<<grade4<<std::endl<<std::endl;
std::cout<<"Average grade: "<<avg<<std::endl;
}
You don't need the static cast here, as you can change the int literal 4 to a double literal 4.0, but if you are summing the elements of a vector then calling size() on it, that will be an integer, and you will have to cast somewhere.

Not understanding why code isn't producing desired answer

The assignment I've been given is asking me to find out how many trees can be put in a certain length and how much total space they'd take up including the required space between the trees. Thanks to some help I've been able to get the tree total correct, but the total space taken up is incorrect. What can I do to fix this.
input is: length = 10, TRadius = .5, ReqSpace = 3
desired output is: TreeTot = 2
Total space should be 1.57
Actual output is: TreeTot = 2 Total Space is 6.1
Here is the code I'm using.
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.14;
int main()
{
double length;
double TRadius;
double ReqSpace;
int TreeTot = 0;
cout << "enter length of yard: ";
cin >> length;
cout << "enter radius of a fully grown tree: ";
cin >> TRadius;
cout << "required space between fully grown trees: ";
cin >> ReqSpace;
while (length > TRadius * 2 + ReqSpace) {
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
}
cout << "The total space taken up is ";
cout << setprecision(2) << TreeTot * TRadius * PI + ReqSpace << endl;
cout << "The total amount of trees is ";
cout << TreeTot;
return 0;
}
These two lines:
TreeTot + 1;
length - (TRadius * 2) + ReqSpace;
are valid statements, but they're just expressions. You calculate a value, but don't do anything with it. TreeTot + 1... and then what? You need to assign the calculated value to something. Presumably you're wanting to increase the TreeTot and decrease the length. Just assign the values like so:
TreeTot = TreeTot + 1;
length = length - (TRadius * 2) + ReqSpace;
Or use the shorthand for modifying and assigning the result to the same value:
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
Your answer will probably still be wrong because the if-statement only runs once - you never tell it you want it to do the code within multiple times. If you change the if to a while then the code will loop until length is too small to satisfy the condition.

Finding the difference between two times of day

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;

C++ Pi Estimating Program Not Working Correctly

I am currently writing a program that estimates Pi values using three different formulas pictured here: http://i.imgur.com/LkSdzXm.png .
This is my program so far:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)
int terms;
bool negatives = false;
cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}
The sample input file that I am using is:
1
6
-5
100
-1000000
0
And the sample output for this input file is:
1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052
When I run my program all I get as an output is:
1 4.000000000000 1.224744871392 1.131370849898.
So as you can see my first problem is that the second and third of my equations are wrong and I can't figure out why. My second problem is that the program only reads the first input value and stops there. I was hoping you guys could help me figure this out. Help is greatly appreciated.
You have three problems:
First, you do not implement the Euler formulae correctly.
π2/6 = 1/12 + 1/22 + 1/32 + ...
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
The square root of the sum is not the sum of the square roots.
π3/32 = 1/13 + 1/33 + 1/53 + ...
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
This is just... wrong.
Second, you increment counter three times in the loop, instead of once:
while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}
Third, and most fundamental, you didn't follow the basic rule of software development: start small and simple, add complexity as little at a time, test at every step, and never add to code that doesn't work.
my first problem is that the second and third of my equations are
wrong and I can't figure out why
Use counter++ just once. Apart from this Leibniz looks fine.
Eulerall is not correct, you should sum all factors and then do sqrt and multiplication at the end:
eulerall = 1/pow(counter+1,2) + eulerall;
// do sqrt and multiplication at the end to get Pi
The similar thing with eulerodd: you should sum all factors and then do sqrt and multiplication at the end.
My second problem is that the program only reads the first input value
and stops there.
In fact this is your first problem. This is because you are incrementing counter multiple times:
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++; // << increment
^^^^^^^^^^
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++; // << increment
^^^^^^^^^^
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++; // << increment
^^^^^^^^^^
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
You should increment counter just once.
You're using the same counter and incrementing it after each calculation. So each technique is only accounting for every third term. You should increment counter only once, at the end of the loop.
Also note that it is generally bad form to use a floating-point value as a loop counter. It only takes on integer values in your program, so you can just make it an int. Nothing else needs to change; the math will run the same because the int will promote to a double when you combine the two in math operations.
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
char* main()
{
while(1)
{
int Precision;
float answer = 0;
cout<<"Enter your desired precision to find pi number : ";
cin>>Precision;
for(int i = 1;i <= Precision;++i)
{
int sign = (pow((-1),static_cast<float>(i + 1)));
answer += sign * 4 * ( 1 / float( 2 * i - 1));
}
cout<<"Your answer is equal to : "<<answer<<endl;
_getch();
_flushall();
system("cls");
}
return "That is f...";
}

Why do I get an Invalid Syntax from print in Python?

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.")