Function returning NaN in C++ - c++

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);
}

Related

Why does the console asks for more inputs? C++

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;
}

how to fix this char array cann't stop printing

Attached Image Someone Please help me fix the this problem.I was using the if statement to determine the material is copper, and then I would like to use arrays to print out different type of length and material. Thank You.
enter code here
#include <stdlib.h>
#include <iostream>
using namespace std;
float steelbar ();
float steelrod ();
char printMenu ();
void testing(float length, float area, float stress, float price);
int main()
{
char Choice;
float result;
cout<<"\t\tWelcome to Smart Calculating System\n";
cout<<"\t\t_______________________________________\n";
Choice = printMenu();
if (Choice == 'A' || Choice == 'a')
{
result = steelbar();
}
else if (Choice == 'B' || Choice == 'b')
{
result = steelrod();
}
else
{
printf("Invalid input!\n");
fflush(stdin);
getchar();
}
}
char printMenu ()
{
char choice;
cout<<" Please choose a type:\n";
cout<<" A/a = Steel bar B/b = Steel rod\n";
cout<<"Answer = "<<endl;
cin>>choice;
cout<<"\n";
return choice;
}
/////////////////////////////////////////////////////////////////
float steelbar ()
{
float length, width, height, pressure, area, stress, price;
int program=1;
while(program == 1)
{
cout<<"Please enter length: "<<endl;
cin>>length;
cout<<"Please enter width: "<<endl;
cin>>width;
cout<<"Please enter height: "<<endl;
cin>>height;
cout<<"Please enter pressure: "<<endl;
cin>>pressure;
area = height * width;
stress = pressure / area;
cout<<"\nThe stress is : "<<stress<<endl;
if (stress <= 690)
{
testing(length, area, stress, price);
fflush(stdin);
getchar();
cout<<"\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = ";
cin>>program;
if (program == 1)
{
printMenu ();
}
else (program == 0);
{
return 0;
}
}
else if (stress > 690)
{
cout<<"\n";
cout<<" Please enter stress less than 690 MPA\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = "<<endl;
system("cls");
}}
return price;
}
/////////////////////////////////////////////////////////////////
float steelrod ( )
{
float length, diameter, pressure, area, stress, price ,density, rate ;
int program;
while(program == 1)
{ cout<<"Please enter length: "<<endl;
cin>>length;
cout<<"Please enter diameter: "<<endl;
cin>>diameter;
cout<<"Please enter pressure: "<<endl;
cin>>pressure;
area = (3.14159 * diameter * diameter) / 4;
stress = pressure / area;
cout<<" The stress is : "<<stress;if (stress <= 690)
{
testing(length, area, stress,price);
fflush(stdin);
getchar();
system("cls");
cout<<"\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = ";
cin>>program;
if (program == 1)
{ system("cls");
main ();
}
else (program == 0);
{return 0;
}
}
else if (stress > 690)
{
cout<<"\n";
cout<<" Please enter stress less than 690 MPA\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = "<<endl;
cin>>program;
system("cls");
}
return price;
}
}
/////////////////////////////////////////////////////////////////
void testing(float length, float area, float stress, float price)
{
const char *material[30];
int i, j;
if( stress <= 70)
{
material[i] = "Copper";
price = length * area * 10 * 1.5;
}
else if( stress >70 && stress <= 130 )
{
material[i] = "Cast iron";
price = length * area * 15 * 1.8;
}
else if( stress >130 && stress <= 200 )
{
material[i] = "Brass";
price = length * area * 17 * 2.0;
}
else if( stress >200 && stress <= 690 )
{
material[i] = "ASTM A51";
price = length * area * 22.5 * 2.20;
}
for(i=0;i<3;i++)
{
cout<<"Material : "<<material[i];
cout<<"\nThe total price is : RM"<<price<<endl;
}
}
I'm not sure about your intent but... I see sime things that are very strange.
(1) in testing(), you define the variable i but you don't assign any value to it; so, when you assign
material[i] = "Cooper";
the value for i is undefined
(2) in printarray(), you definition of material is
float material[i], price;
where i is a parameter of the function (with undefined value, if received from testing()); this isn't standard C++ because you can't define a C-style array (but was your intention?) with a not-known at compile time dimension
(3) in printarray() you define material as a float array of size i and you don't initialize the i values; so material carry i undefined values; when you acess it in the following for
for(i=0;i<3;i++)
{
cout<<"Material : "<<material[i];
cout<<"\nThe total price is : RM"<<price<<endl;
}
you access 3 undefined values
(4) according the image you report us, with
cout<<"Material : "<<material[i];
you print a C-style string (char *) with values "Cooper", some garbage (uninitialized values) and empty string; according the code you show us, material should be an array of float. I deduce that the image you show us is generated by a different code. Please, show us the corrispondent (and complete) code
(5) sorry for my bad English

Stuck on a c++ lucky seven game program

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;
}
}

How to average positive inputs until a negative input is given

How can I accept and average positive numbers? When a negative number is entered, it should terminate the loop and display the average (excluding the negative number).
#include <iostream>
using namespace std ;
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
if(x<0) {
sum+=x;
counter++;
continue;
} else if (x>0) {
cin>>x;
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
#include <iostream>
using namespace std;
int main() {
int sum = 0, count = 0, input; // initialize all variables
while (true) { // loop forever (until break is reached below)
cin >> input; // get user input
if (input < 0) break; // if it's negative, exit loop
sum += input; // otherwise add it to the running sum
count++; // increase the count by 1
}
if (count > 0) cout << (double)sum / count; // if we have at least one number, display avg
else cout << "No numbers to average" << endl; // else complain.
return 0;
}
Note that this will fail if the user provides bad input. If you need it to handle bad input, see here about cin types.
The implementation that you have immediately adds the input to your sum.
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
cin >> x;
if (x>0) {
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
This would allow you to check the input before adding to your total.
It is also important to mention to avoid dividing by zero if the user's first input is a negative number.
here is an improved version, that checks if loop exist without any positive integers entered to avoid divide by zero error
#include <iostream>
using namespace std ;
int main () {
int x;
float counter=0,sum;
float avg;
bool isPositive = true;
while ( isPositive) {
cin>>x;
if(x>0)
{
sum+=x;
counter ++;
}
else {
isPositive = false;
}
}
// if we divide by zero, an error will occur
if(counter > 0)
{
avg=(float)(sum/counter);
cout<<avg<<endl;
}
else cout << "Please enter positive numbers";
return 0 ;
}

Basic C++ Dice game

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.