Created
September 28, 2011 13:36
-
-
Save grodtron/1247947 to your computer and use it in GitHub Desktop.
class assignment 2 - mostly about loops and stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Write a program that estimates the inflation rate for the past year. The program prompts the user for | |
* the current and last year prices of a representative item (e.g., milk, bread, etc.). It then calculates and | |
* prints the inflation rate (as a percent value) by analyzing the price difference. In addition, the program | |
* prints out an estimate, based on the calculated inflation rate, of the price of the item one and two years | |
* hence. Your program should allow the user to repeat the estimation as often as the user wishes. Use | |
* functions to calculate the inflation rate and the price estimation. | |
* | |
*/ | |
#include <iostream> | |
#include <stdio.h> | |
using namespace std; | |
int main(int argc, const char *argv[]) | |
{ | |
float | |
currPrice = 0, | |
prevPrice = 0, | |
currInflation = 0, | |
avrgInflation = 0; | |
for (float i = 1; true; i++) { | |
// get input | |
cout << "enter the price of an item last year, followed by its price this year. Enter 0 for either value to quit: "; | |
cin >> prevPrice; | |
if(!prevPrice){ return 0; } | |
cin >> currPrice; | |
if(!currPrice){ return 0; } | |
//calc current Inflation change | |
currInflation = currPrice / prevPrice; // to get the change in percent | |
// output the estimated price based on the inflation for that item | |
printf("Based on an inflation rate of %.2f%, the price next year will be $%.2f and the price in two years will be $%.2f\n", | |
(currInflation - 1) * 100, currPrice * currInflation, currPrice * currInflation * currInflation | |
); | |
// calculate running average of inflation values (just for fun) | |
avrgInflation = (avrgInflation * ( ( i - 1) / i ) ) + (currInflation / i); | |
// if this is not the first iteration, output the new values based on the average inflation rate | |
if(i > 1){ | |
printf("Based on an average inflation rate of %.2f%%, the price next year will be $%.2f and the price in two years will be $%.2f\n", | |
(avrgInflation - 1) * 100, | |
currPrice * avrgInflation, | |
currPrice * avrgInflation * avrgInflation | |
); | |
} | |
// output a blank line to make it look nice | |
cout << endl; | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
bool isPerfect(int n){ | |
int ub = (int) ceil(sqrt(n)); | |
int sum = 1; | |
for (int i = 2; i < ub; ++i) { | |
if(n % i == 0){ | |
sum += i; | |
sum += (n/i); | |
} | |
} | |
if(ub*ub == n){ | |
sum += ub; | |
} | |
return n == sum; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
using namespace std; | |
for (int i = 0; i < 10000; i++) { | |
if(isPerfect(i)){ | |
cout << i << endl; | |
} | |
} | |
return 0; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* PROBLEM STATEMENT: | |
* | |
* Write a program that inputs a lower and an upper range and then finds and prints all prime numbers in | |
* that range. A prime number is a number such that one and itself are the only numbers that evenly | |
* divide it. For example for the range [3, 20] the program should output the following: 3, 5 , 7 , 11, 13, | |
* 17, 19. | |
* | |
* For this task I'll use the "Sieve of Eratosthenes" to calculate the primes | |
* it is fairly straight forward and is explained below. | |
* | |
* input is given via command line arguments, their order does not matter | |
* | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
using namespace std; | |
// has to be declared as int not void or else compiler complains when used in the short circuit below | |
// ("void value not ignored as it ought to be") | |
int die(const char * message){ | |
puts(message); | |
exit(0); | |
return 0; // will never get here, but needs a return val | |
} | |
// with some help from http://www.java2s.com/Code/C/Pointer/SwapfunctionExchangethevaluesbypointers.htm | |
void swap(int *a, int *b){ | |
int c = *a; | |
*a = *b; | |
*b = c; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
// short circuits! | |
argc == 3 or die("expecting exactly 2 arguments (upper and lower bounds)."); | |
int lowerBound, upperBound; | |
lowerBound = atoi(argv[1]); | |
upperBound = atoi(argv[2]); | |
// eliminate any human error in reversing the arguments | |
if (lowerBound > upperBound) swap(&upperBound, &lowerBound); | |
// to calculate all the primes we will use the Sieve of Eratosthenes | |
// ( http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes ) | |
// unfortunately this requires getting all primes from 2 to max | |
// this is really inefficient if the lower and upper bounds are both | |
// really high, for example [10000,10020], but in most normal | |
// cases I think it should be the best approach. I'm sure there's | |
// some good way to figure out the optimal method for a given range, | |
// but I'm not too concerned about that. | |
int range[upperBound - 1]; | |
// fill the sieve with all ints from 2 to upperBound | |
for(int i = 0; i < (upperBound - 1); ++i){ | |
range[i] = i + 2; | |
} | |
// this boolean keeps track of whether we've printed any prime to the | |
// screen yet, so that the formatting ends up being nice, and there is | |
// no trailing ", " | |
bool haventPrintedYet = true; | |
for(int i = 0; i < (upperBound - 1); ++i){ | |
// if the current entry is not 0, it means it is prime | |
if(range[i]){ | |
// so we set up some temp variables and then loop through, filtering out | |
// every number in the range that is a multiple of the number we have now | |
int p = range[i]; | |
int j = i + p; | |
while(j < (upperBound - 1)){ | |
range[j] = 0; | |
j += p; | |
} | |
// as explained above, make sure the formatting is good. | |
if(p >= lowerBound){ | |
printf(haventPrintedYet ? "[ %d" : ", %d", p); | |
haventPrintedYet = false; | |
} | |
} | |
} | |
puts(" ]"); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* PROBLEM STATEMENT: | |
* | |
* A newly installed vending machine sells DVDs for $15. Inside every DVD is a coupon. 6 coupons | |
* are needed to get one DVD for free. Write a program that inputs the number of dollars and outputs | |
* how many DVDs a customer can collect after spending all cash money and redeeming as many | |
* coupons as possible. The program should also output the number of leftover coupons. | |
* | |
* For example, if customer “John” has 500 dollars then he can initially buy 33 DVDs. This gives him | |
* 33 coupons. He can redeem 30 coupons for 5 additional DVDs. These 5 additional DVDs have 5 | |
* more coupons, so we now have a total of 8 coupons when added to the 3 remaining coupons from the | |
* original purchase. This gives John enough to redeem one final DVD. As a result John has received | |
* 39 DVDs and still has 3 leftover coupons. | |
*/ | |
/* | |
* First the basics: | |
* inputs: | |
* dollars | |
* outputs: | |
* number of DVDs | |
* | |
* | |
* Algorithm: | |
* - first step is to get the initial number of DVDs based on the dollar amount | |
* - after this is done we need to iteratively calculate how many DVDs can | |
* be purchased using tokens | |
* - each iteration we spend coupons and get back a smaller number of coupons and some DVDs | |
* - we repeat this until we can no longer buy any DVDs with the number of coupons we have. | |
*/ | |
#include <iostream> | |
#include <stdio.h> | |
#include <math.h> | |
using namespace std; | |
int main() | |
{ | |
const float DOLLAR_COST_OF_DVD = 15.00; | |
const int COUPON_COST_OF_DVD = 6; | |
float inputAmount; | |
int | |
DVDs = 0, | |
coupons = 0; | |
// get input from the user | |
cout << "enter the amount of money to be spent: "; | |
cin >> inputAmount; | |
// calc the initial number of DVDs purchased / coupons obtained | |
DVDs = (int)floor(inputAmount / DOLLAR_COST_OF_DVD); | |
coupons = DVDs; | |
int newDVDs = 0; | |
while(coupons >= COUPON_COST_OF_DVD){ | |
newDVDs = coupons / COUPON_COST_OF_DVD; // this works because int division is truncated towards zero, not rounded | |
coupons = coupons % COUPON_COST_OF_DVD; // the coupons that remain is the remainder of the int division | |
coupons += newDVDs; | |
DVDs += newDVDs; | |
} | |
printf("with $%.2f you can buy %d DVDs. You will have %d coupons left over\n", inputAmount, DVDs, coupons); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* During winter, meteorologists often report the so-called wind chill factor, which takes into account the | |
* wind speed in addition to the temperature. The wind chill factor for a given temperature (in | |
* Celsius) and wind speed may be approximated by the following formula: | |
* | |
* w = (9/200)(5.27sqrt(v) + 10.45 - 0.28v)(t - 33) + 33 | |
* | |
* where | |
* v = wind speed in m/sec | |
* t = temperature in degrees Celsius: t <= 10 | |
* w = wind chill index (in degrees Celsius) | |
* | |
* Write a program that prompts the user for the current temperature and wind speed and then outputs the | |
* corresponding wind chill index. Note that the user should be given the choice between entering the | |
* temperature in Celsius or Fahrenheit. Use functions for the wind chill calculation and the conversion | |
* between Celsius and Fahrenheit (and vice versa). Your code should ensure that restrictions on the | |
* temperature for calculating the wind chill are not violated. | |
* | |
* Gordon Bailey for Dr. Daniel Sinnig's COEN 243, fall 2011 | |
* | |
*/ | |
#include <math.h> | |
#include <string> | |
#include <iostream> | |
#include <cstdlib> | |
#include <stdio.h> | |
using namespace std; | |
float windchill(float v, float t) | |
{ | |
printf("windspeed: %.2f temp: %.2f\n\n", v, t); | |
return (9.0/200.0)*((5.27*sqrt(v)) + 10.45 - (0.28*v))*(t - 33.0) + 33.0; | |
} | |
float farenheitToCelsius(float f){ | |
return 0.5555555555555555*(f-32); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
float windspeed, temperature; // (temperature in C) | |
string tempStr; | |
// get inputs from user | |
cout << "enter the wind speed (in metres / second): "; | |
cin >> windspeed; | |
cout << "enter the temperature (add a C or F suffix to specify units, Celcius is default): "; | |
cin >> tempStr; | |
// calculate temperature based on input value and unit | |
// accepted temperatures are in the format "x", "xc", "xC", "xf", "xF" | |
// where x is a numerical string, e.g "1", "2.34", "-5.67" | |
// first we find the first occurence of any of the characters that | |
// represents a unit. The default unit is 'c'. | |
size_t pos = tempStr.find_first_of("fFcC"); | |
char unit = 'c'; | |
// if we could find a unit character then we extract it and then take the | |
// substring up to, but not including, that character | |
if (pos != string::npos){ | |
unit = tempStr[pos]; | |
tempStr = tempStr.substr(0, pos); | |
} | |
// we then convert the resultant string to a float value | |
// there is no validation/error correction right now... | |
temperature = atof(tempStr.c_str()); | |
// based on the unit we convert the temperature to Celsius if necessary | |
if(unit == 'f' || unit == 'F'){ | |
temperature = farenheitToCelsius(temperature); | |
} | |
if(temperature > 10.0){ | |
printf("The temperature you entered (%.2f degrees C) is too warm (it should be less than 10.00 degrees C)\n\n", temperature); | |
return 0; | |
} | |
printf("the windchill makes it feel like %.2f degrees.\n\n", windchill(windspeed, temperature)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment