I am trying to make a program where I calculate fees based on the ride type and time the user rented stuff. I came up with the method of how to do it, but when I try to read input the console keeps asking for more input.
double computeFee(){
double fee, hour_rate, minute_rate;
char ride_type, colon;
int hour_started, minute_started, hour_ended, minute_ended, total_minutes;
cin >> ride_type >> hour_started >> colon >> minute_started >> colon >> hour_ended >> colon >> minute_ended;
total_minutes = ((hour_ended * 60) + minute_ended) - ((hour_started * 60) + minute_started);
switch(ride_type){
case 'J':
hour_rate = 500;
minute_rate = 10;
break;
case 'K':
hour_rate = 200;
minute_rate = 5;
break;
case 'B':
hour_rate = 100;
minute_rate = 2;
break;
case '0':
return 1;
break;
}
if (total_minutes < 60){
fee = total_minutes * minute_rate;
}else{
fee = ((total_minutes/60) * hour_rate) + ((total_minutes%60) * minute_rate);
}
return fee;
}
int main(){
double total, fee;
computeFee();
fee = computeFee();
cout << fee;
return 0;
}
Each time you call computeFee(), the function code is executed. In your code, you call it twice, so it will ask you for the input two times. And given that the first time you call it you don't assign it, the first input will be lost.
To make it work the way you want, your main code should be:
int main(){
double fee;
fee = computeFee();
cout << fee;
return 0;
}
Related
I am currently writing a program for a class involving code for a Grade Point Average calculator with added features. My code was working right up until I added my last line of code for the sum of the grades and subsequent division for the average. I feel like I'm missing something obvious here, but I'm at a loss, currently. Ideally, this program would be accepting input from a user at four separate points, adding the input together, and then dividing it by 4 (as the current number of grades I have code for is 4, but I plan on increasing this amount once I figure out how to solve this issue).
Initially, I was getting errors because I was asking the code to translate a double variable into a char variable and then back into a double variable (error code C4244). I also changed the end of the code to declare the sum of all grades as a separate variable, because including it all in one variable, GPA, resulted in the program outputting a seemingly random number. I since changed my code to flow more evenly, however now when I execute the program, it asks for the initial input for the first grade then skips right over the second, third, and fourth grades.
I'm still extremely new to C++, so I may be over complicating my code, but I'm stumped.
#include <iostream>
using namespace std;
int GPAAndHonorsCalculator;
int main()
{
//Declaring initial values
double A = 4.0;
double B = 3.0;
double C = 2.0;
double D = 1.0;
double F = 0.0;
double GPA = 0.0;
//Created if else statements to handle user input and translation into data for the program to use.
cout << "Please enter your first grade: " << endl;
double gradeOne = 0.0;
cin >> gradeOne;
if (gradeOne == 'A') {
gradeOne = 4.0;
}
else if (gradeOne == 'B') {
gradeOne = 3.0;
}
else if (gradeOne == 'C') {
gradeOne = 2.0;
}
else if (gradeOne == 'D') {
gradeOne = 1.0;
}
else if (gradeOne == 'F') {
gradeOne = 0.0;
}
cout << "Please enter your second grade: " << endl;
double gradeTwo = 0.0;
cin >> gradeTwo;
if (gradeTwo == 'A') {
gradeTwo = 4.0;
}
else if (gradeTwo == 'B') {
gradeTwo = 3.0;
}
else if (gradeTwo == 'C') {
gradeTwo = 2.0;
}
else if (gradeTwo == 'D') {
gradeTwo = 1.0;
}
else if (gradeTwo == 'F') {
gradeTwo = 0.0;
}
cout << "Please enter your third grade: " << endl;
double gradeThree = 0.0;
cin >> gradeThree;
if (gradeThree == 'A') {
gradeThree = 4.0;
}
else if (gradeThree == 'B') {
gradeThree = 3.0;
}
else if (gradeThree == 'C') {
gradeThree = 2.0;
}
else if (gradeThree == 'D') {
gradeThree = 1.0;
}
else if (gradeThree == 'F') {
gradeThree = 0.0;
}
cout << "Please enter your fourth grade: " << endl;
double gradeFour = 0.0;
cin >> gradeFour;
if (gradeFour == 'A') {
gradeFour = 4.0;
}
else if (gradeFour == 'B') {
gradeFour = 3.0;
}
else if (gradeFour == 'C') {
gradeFour = 2.0;
}
else if (gradeFour == 'D') {
gradeFour = 1.0;
}
else if (gradeFour == 'F') {
gradeFour = 0.0;
}
int gradeSum = gradeOne + gradeTwo + gradeThree + gradeFour;
GPA = gradeSum / 4;
cout << GPA;
}
At the suggestion of #LukeH, I cleaned up my code and made a nested while switch statement. Here is part of the working code:
int main() {
//Declaring initial values, as well as initializing a counter for later loop.
int gradeValue = 0;
int gradeCount = 0;
char userGrade = 0;
double GPA = 0.0;
//Creating while loop with switch statement nested inside to handle large amounts of repeating code.
while (gradeCount!= 4) {
cout << "Please enter a grade (A, B, C, D, or F): ";
cin >> userGrade;
switch (userGrade) {
case 'A': {
gradeValue = gradeValue + 4;
++gradeCount;
break;
}
I repeated this process for each grade and it worked a treat!
I commented earlier, but I figured I'd elaborate a bit more if it could help further.
As it seems you have already figured out, you were trying to store a character in a double variable which will either break your code or have some serious unexpected results. Unlike languages like Javascript, variables in C++ have a defined type and cannot change between, say, a double and a string. In your edited code you seemed to have accounted for this and it seems your code is now functioning better.
One important thing to note, especially as it seems you are still learning, is there should be a little internal alarm that goes off in your head as a programmer anytime you are writing blocks of code that are the same or very similar to code you have already written. The saying "DRY" or "Don't Repeat Yourself" is very popular for a reason and can help your code be much easier to read, write, and edit.
For your example, the main function has all of your logic in it and as it gets longer and longer it can be hard to interpret what is happening in the written code. Your code is roughly:
int main() {
//Declaring initial values, as well as initializing a counter for later loop.
int gradeValue = 0;
int gradeCount = 0;
char userGrade = 0;
double GPA = 0.0;
//Creating while loop with switch statement nested inside to handle large amounts of repeating code.
while (gradeCount!= 4) {
cout << "Please enter a grade (A, B, C, D, or F): ";
cin >> userGrade;
switch (userGrade) {
case 'A': {
gradeValue = gradeValue + 4;
++gradeCount;
break;
}
case 'B': {
gradeValue = gradeValue + 3;
++gradeCount;
break;
}
case 'C': {
gradeValue = gradeValue + 2;
++gradeCount;
break;
}
case 'D': {
gradeValue = gradeValue + 1;
++gradeCount;
break;
}
case 'F': {
++gradeCount; // no need to add to value since F=0
break;
}
}
// logic to display GPA
// TODO
If you instead put the user input logic in its own function, your main() will be much cleaner. An added benefit is that if you need to update the logic for getting input (like you did once already!), your main() function doesn't need to change at all.
Your main() would look something like this then:
int main() {
// declare variables
double gradeValue = 0.0;
int gradeCount = 0;
// get input
while(gradeCount < 4) {
gradeValue += getUserGrade(); // add grade to GPA
gradecount++;
}
// logic to display GPA
// TODO
}
Much easier to understand right? In your getUserGrade() function you would just need to have your switch statement logic and return a double value of the grade they input. I left out the logic to display GPA just because this is an assignment and that part is up to you to finish.
With this simpler framework in place, you can easily adjust the code to be able to handle as many grade inputs as the user wants to give. If you just have an option for the user to type "done" or something else significant when they are asked for a grade, you can return a special value that your code in main() can use to know when to stop taking input (-1.0 would work because that would not be a valid GPA). Your main() would look something like this then:
int main() {
// declare variables
double gradeValue = 0.0;
int gradeCount = 0;
// get input
while(true) {
double usrInput = getUserGrade();
if(usrInput == -1.0) break; // exit loop if user is done
gradeValue += usrInput;
gradecount++;
}
// logic to display GPA
// TODO
}
With only changing a few lines of code, you can now have a program that is much more flexible!
Firstly, what are you using the variables A, B,C, D, F for? Secondly you can't use double type variable to store characters. Just use a char variable to get the input grade and set the grade variable accordingly. Also if you plan to add more of these grades, then it will be better for you to either write it in a function and call it again and again(or put the function call in a loop) so that repetition of code is avoided and the code in general looks cleaner.
I'm creating a software in C++ loops on one function(double) indefinitely. After going through the loop the first time, the second time it runs, it returns 'nan'. Where did I go wrong.
int main()
{
double Balance = 100;
for (int i = 0; i < 5; i++) {
nyaradzo(Balance, i);
}
}
double nyaradzo(double bal, int pass)
{
int x = bal;
double Amount;
string policy_number;
double confirmation;
cout<<"WELCOME TO NYARADZO ONLINE POLICY PAYMENT"<<endl;
cout<<"ENTER YOUR POLICY NUMBER"<<endl;
cin>>policy_number;
cout<<"ENTER AMOUNT YOU WISH TO PAY FOR YOU POLICY"<<endl;
cin>>Amount;
cout<<"YOUR POLICY NUMBER IS: "<<policy_number<<endl;
cout<<"YOU HAVE CHOSEN TO PAY $"<<Amount<<" FOR YOUR FUNERAL POLICY. \n Is this information correct?"<<endl;
cout<<"1 TO CONFIRM"<<endl;
cout<<"2 TO CANCEL"<<endl;
cin>>confirmation;
if (confirmation==1) {
if (Amount <= x) {
x -= Amount;
cout<<"Transaction Complete"<<endl;
cout<<"YOUR BALANCE IS $"<<x<<endl;
return x;
}
else if (Amount > x) {
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"You cannot withdraw more than your actual balance..."<<endl;
return 0;
}
else {
cout <<x << endl;
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"Your purchase must be greater than or at least equal to $1"<<endl;
return 0;
}
}
else if (confirmation==2) {
cout<<"YOU HAVE CHOSEN TO CANCEL YOUR ZESA TRANSACTION"<<endl;
// transaction(bal, pass);
}
else
{
cout << "Invalid selection" << endl;
return 0;
}
}
When it goes through the loop a second time, it fails.
Not all paths in nyaradzo return a value. You should enable all your compiler warnings. It should alert you of this. Since x = bal and you only modify x when the amout is ok, add this as the final line of the func:
return x;
And change type of x to double. Or get rid of x and use bal throughout.
Also, I assume you want to keep a running balance. Then you should change the for loop to:
for (int i = 0; i < 5; i++) {
Balance = nyaradzo(Balance, i);
}
My Basic Algorithm:
Ask for input money amount; Rolls two 6-sided dice; if they add up to 7, add 4 to money amount; else, subtract 1 from money amount; loop until moneyamount<0; loop game user says n when prompted to play again.
/*
*File: hw3
*Author: Nathaniel Goodhue
*
*Created on: 9/15/15
*Description: Game of lucky sevens
*
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
srand (time(NULL));
double moneyAmount;
int winValue = 7;
int numRolls = 0;
char playAgain = 'y';
while(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
while(moneyAmount>0)
{
int roll1= (rand()%6)+1;
int roll2 = (rand()%6)+1;
if(roll1+roll2 == winValue)
{
moneyAmount+=4;
numRolls++;
}
else
{
moneyAmount-=1;
numRolls++;
}
}
cout<<"It took "<<numRolls<<" roll(s) to lose all of your money"<<endl;
// cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
cout<<"Play again? y/n"<<endl;
cin>>playAgain;
if(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
numRolls = 0;
}
else
{
break;
}
}
return 0;
}
Above is my current code. It works as intended. What I am stuck on is that I need to be able to implement this line of code right after money drops below 0:
cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
I need to find out when there was the most money and after how many rolls that it appeared. The maxAmount variable would be the max amount of money achieved, and the maxRolls variable would be the number of rolls when maxAmount was reached.
This is pretty simple to add to your code. What you can do is check if the amount of money they have is greater than the max amount of money. If it is then set max to current and record the number of turns it took to get that value.
int maxAmount = moneyAmount, maxRolls = 0;
while(moneyAmount > 0)
{
int roll1 = (rand() % 6) + 1;
int roll2 = (rand() % 6) + 1;
numRolls++;
if(roll1 + roll2 == winValue)
moneyAmount += 4;
else
moneyAmount -= 1;
if (moneyAmount > maxAmount)
{
// the current amount of money is greater than the max so set max to current and get the number of rolls
maxAmount = moneyAmount;
maxRolls = numRolls;
}
}
I have a problem here, would be really nice if anyone could help me out here. Its my first time using this program so dont be to judgemental.
#include <cstdlib>
#include <iostream>
using namespace std;
int throw1, throw2, throw3, throw4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3);
int deposit;
int account;
int main(){
int count = 0;
while(count < 3){
cin>>deposit;
while(deposit>5000 || deposit<0){ //Makes sure so that my deposit is between 0-5000
cout<<"deposit failed"<<endl;
cin>>deposit;
}
account = deposit;
cout<<"You have deposited" <<deposit<<"Swedish Krona"<<endl;
cout<<"and you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
if (konto>499){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet2=300, bet3=500"<<endl;
cin>>bet1;
cin>>bet2;
cin>>bet3;
account = (deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>299){
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet=300"<<endl;
cin>>bet1;
cin>>bet2;
account =(deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>99){
cout<<"please place your bet"<<endl;
cout<<"bet1=100"<<endl;
cin>>bet1;
cout<<"you have placed your bet"<<bet<<"Swedish Krona"<<endl;
}
while (account<100 || deposit>5000){
cout<<"insufficient funds"<<endl;
cin>>deposit;
account=deposit;
}
{
cout<<"Throw dice"<<endl;
srand(time(0));
Throw1 = rand() % 6 + 1;
Throw2 = rand() % 6 + 1;
Throw3 = rand() % 6 + 1;
Throw4 = rand() % 6 + 1;
cout<<"You rolled"<<Throw1<<endl;
cout<<"You rolled"<<Throw2<<endl;
cout<<"Computer rolled"<<Throw3<<endl;
cout<<"Computer rolled"<<Throw4<<endl;
}
}
count++;
system ("pause");
}
So the thing here is that, for some reason i always bet 500, even though type in bet1 or bet2, and i have no clue how to fix that problem. And then my loop function (int count 0; while(count < 3)count++) it starts to loop endlessly without me pressing anything, even though i use the same loop function in simple coding like just typing some cout<< things it works fine, but when i use it in this code, it goes to drain, do anyone know why this is happening, would appreciate if anyone could answer, thanks in advanced.
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3)
The last line will be evaluated like this: 100, 300, 500. Result of comma separated list of expression will be last value, which is 500. So your bet variable will be always set to 500.
What you state in your comment below the code, (int count 0; while(count < 3)count++)looks like some weird mixture of for and while loop. Please check again your C++ textbook/online tutorials about how to write a correct loop.
In the code you show, in your while loop, you don't modify the count variable - therefore it will loop forever if count is < 3 before the loop. The indentation of your code is really misleading. I have taken the liberty of reformatting your code - and now you should see that the count++ statement actually is outside of your main while loop!
When you want to do something for a fixed number of times, it's recommendable to use a for loop, it makes it harder to forget the increment!
You increase count outside the loop, so it will always be zero. Either move it inside the loop (proper indentation is key!) or maybe use a for loop instead:
for (count = 0; count < 3; ++count) { ... }
Some advice,
place your prompt for deposit (insattning) into a function
place your prompt for bet into a function
check for sufficient money before prompting for bet
get input into a string, then validate input (not done below, yet)
check that bet is valid (=100,=300,=500, bet<=konto)
Here are these convenience functions,
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
int kast1, kast2, kast3, kast4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=0; //assignment didn't make sense
int insattning=0;
int konto=0;
//deposit
int get_insattning()
{
int good = 0;
while( !good )
{
cout<<"deposit"<<endl; //prompt for deposit
cin>>insattning;
if(insattning>5000 || insattning<0)//Makes sure so that my deposit is between 0-5000
{
cout<<"insattning fel, var vänlig och gör rätt denna gången"<<endl;
}
else good = 1;
}
cout<<"du har nu satt in" <<insattning<<"kr"<<endl;
return insattning;
}
It isn't clear to me whether you want 1 bet of 100,300,or 500, or 3 bets. This does the first,
//bet
int get_bet()
{
int good = 0;
int bet;
std::string validbets = "";
if(konto<100){ cout<<"you need more money"; return 0; }
while( !good )
{
cout<<"var vänlig och placera ditt bet"<<endl;
if(konto>=100){ validbets = "bet1=100"; }
if(konto>=300){ validbets += ", bet=300"; }
if(konto>=500){ validbets += ", bet=500"; }
cout<<validbets<<endl;
cin>>bet;
if( bet >= konto ) {
cout<<"you don't have enough money"<<endl;
continue;
}
if (bet==500){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"du har så här mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==300){
cout<<"du har så mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==100){
cout<<"du har nu bettat "<<bet<<" kr"<<endl;
good = 1;
}
else {
cout<<"you must place valid bet"<<endl;
continue;
}
}
return bet;
}
Now your main game play is cleaner/easier to read. I don't know what the win conditions are or the payout, and since your prompts are not english, I cannot read them to tell what to do next,
int main()
{
int count = 0;
int bet;
srand(time(0));
for( count=0; (count < 3); count++)
{
konto = get_insattning();
if (konto<100)
{
cout<<"du har inte nog med pengar, vänligen sätt in pengar"<<endl;
continue;
}
cout<<"och du har så här mycket i ditt konto "<<konto<<" kr"<<endl;
bet = get_bet();
//when you bet, reduce konto by bet
konto = (konto - bet);
{
cout<<"slå tärningar"<<endl;
kast1 = rand() % 6 + 1;
kast2 = rand() % 6 + 1;
kast3 = rand() % 6 + 1;
kast4 = rand() % 6 + 1;
cout<<"Du fick"<<kast1<<endl;
cout<<"du fick"<<kast2<<endl;
cout<<"datorn fick"<<kast3<<endl;
cout<<"datorn fick"<<kast4<<endl;
}
You need to write code for determining whether you won or lost, and then add to konto when you win,
//did you win or lose?
//win? add money to konto
//lose? you have already deducted from konto
}
system ("pause");
}
These suggestions should help you fix your program.
This is what I have so far. It won't work. I'm trying to write it to get user input of an amount and the county they live in and the program outputs the total with taxes
#include<iostream>
using namespace std;
int main()
{
char amt = 0;
double county ;
char x = 0;
double total = 0;
total = amt + x;
x = county;
printf("\nplease enter amount\n");
scanf_s("%d",&amt);
printf("\nplease enter county\n");
scanf_s("%c",&x);
scanf_s("%c",&total );
printf("total:", amt * x);
switch(x)
{
case 'o':
printf("orange:",county = 0.06);
break;
case 'l':
printf("lake:",county = 0.07);
break;
case 's':
printf("seminole:",county = 0.08);
break;
}
system("pause");
}
When you use printf(), also specify which variables you are sending, so if you want to print a value use something like: printf("Value: %f\n", 0.07);.
You can find the format specifiers here.
You should put the switch clause before the line where you print the total. Also, from what I'm seeing you shouldn't multiply the amt * x but something like subtotal * (1 + county)
If scanf_s() is anything like scanf(), you should consider using the right conversions for the arguments ("%d" means 'int' and so on).