-
-
Save MggMuggins/f2e68e7aff1e12ce0b6e8c720c0a4279 to your computer and use it in GitHub Desktop.
import std.stdio; | |
float readValue (string text) { | |
float output; | |
write(text); | |
readf(" %s", &output); | |
return output; | |
} | |
void printOut (float large, float small) { | |
writeln("Range: ", small, "-", large); | |
} | |
int main() { | |
float itemPrice, diff, large, small, oddAverage; | |
while (1 == 1) { | |
try { | |
itemPrice = readValue("Item Price? "); | |
} catch (std.conv.ConvException) { | |
return 0; | |
} | |
oddAverage = itemPrice / 2 + 0.5; | |
if (itemPrice % 2 == 0) { | |
if (itemPrice % 4 == 0) { | |
diff = itemPrice / 4; | |
large = itemPrice + diff; | |
small = itemPrice - diff; | |
printOut(large, small); | |
} else { | |
diff = itemPrice / 4 + 0.5; | |
large = itemPrice + diff; | |
small = (itemPrice - diff) + 1; | |
if (itemPrice == 2) { | |
small = small - 1; | |
} | |
printOut(large, small); | |
} | |
} else { | |
if (oddAverage % 2 != 0) { | |
diff = (oddAverage / 2) + 0.5; | |
large = itemPrice + diff; | |
diff = (oddAverage / 2) + 0.5; | |
small = itemPrice - diff; | |
printOut(large, small); | |
} else { | |
diff = oddAverage / 2; | |
large = itemPrice + diff; | |
small = itemPrice - diff; | |
printOut(large, small); | |
} | |
} | |
} | |
} |
Alright, so when something happens during the program's execution that it does not expect (Such as storing any other type of character as type float, which would be exactly what is happening in this case), then it "Throws" something called an "Exception". Usually exceptions kill your program by default. However, it is possible to "Catch" an exception, and handle it in whatever way you want, rather than just letting it close your program. In this instance, if you try to put anything other than a valid float value (Try inputting "q", or any other char!), then it will catch the exception std.conv.ConvException and return 0 instead of continuing with execution, and instead of printing out a ridiculous number of errors complaining about you putting a "q" instead of a number. Does that make sense?
Yep. Amazingly, 'r' is not a price :)
Yeah, pretty much the point of that. There would be cleaner ways to do that, such as reading to an intermediary type (Such as char or string) and then converting that, and depending on what it is, the program would behave differently. However, this makes more sense for a little program like this. It's easier.
And what's this little code do?