how do I get the change of a number - c++

I cannot get the method to output the last lines, help?
Tried the nested if statments, for and do whiles, while is my new default
double cashpay = 0.00;
int doll = 0;
double quart = 0.0;
double dime = 0.0;
double nic = 0.0;
double penn = 0.0;
int c = 0;
cout << "Please input a number less than 5.00: ";
cin >> cashpay;
if (cashpay <= 5.00) {
while (c >= 0) {
while (c / 1 != 0) {
doll += 1;
c -= 1;
}
while (c / .25 != 0) {
quart += .25;
c -= .25;
}
while (c / .1 != 0) {
dime += .1;
c -= .1;
}
while (c / .05 != 0) {
nic += .05;
c -= .05;
}
while (c / .01 != 0) {
penn += 0.01;
c -= .01;
}
}
cout << " " << endl;
cout << doll << " dollars, ";
cout << quart << " quarters, ";
cout << dime << " dimes, ";
cout << nic << " nickles, and ";
cout << penn << " pennies " << endl;
} else {
cout << "Error. Please enter a number under 5.00" << endl;
}
only gives either the input and then possibly the greater than line, no more/less

In general, this problem is solved in the following pseudo-code:
Let there be four vars of unsigned int: quart(0), dime(0), nick(0), penn(0);
While THE AMOUNT OF CHANGE REMAINING is greater than $.00:
Select the largest value ($.25) or ($.10) or ($.05) or ($.01) that is NOT GREATER than the AMOUNT OF CHANGE REMAINING;
Increment quart or nick or dime or penn as above;
Subtract the selected value from THE AMOUNT OF CHANGE REMAINING;
Return {quart, dime, nick, penn}.

Related

C++ Putting a character into a cin for a while loop causes the loop to execute outside of it [duplicate]

This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
(4 answers)
Closed 5 years ago.
I decided to try to make a little game. It's a simple survival game. Part of it has people try to survive as long as they can by choosing options. I've scaled down the game as much as possible from 1000 lines to this for the minimum case.
At one part of the game it asks, "You were visited by a gifting clown. On a scale of 0-10, how badly do you want a gift?"
If they answer 0-10, the loop works fine. If they answer with a character, like y or n, the loop basically forces the game to execute where it no longer asks players for input on any other choices.
A previous while loop works, one where it will continue so long as the player is alive. This clown while loop is nested inside of it. I have broken up the while loop with the clown section to where I think the problem is... And also included the full code just in case it's not inside there.
My goal is simply if a character is put into it, that it doesn't break this game.
main.cpp - clown section
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
main.cpp - Condensed code
#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
int randNumber = 0;
int food = 4;
int wood = 4;
int medicine = 2;
int bullets = 8;
int money = 25;
int randomEncounter = 0;
int hunt = 0;
bool axe = false;
int axeTemp = 0;
int axeBonus = 0;
int lumberTemp = 0;
int lumber = 0;
int findStore = 0;
int storeChoice = 0;
bool gun = false;
int gunSearch;
int gunTemp;
int gunBonus = 0;
int gunFind = 0;
// int searches;
// int searchesBonus;
int farmFind = 0;
int farmFood = 0;
int farmSearch = 0;
bool farm = false;
string description;
int foodTemp = 0;
int woodTemp = 0;
int medicineTemp = 0;
int bulletsTemp = 0;
int moneyTemp = 0;
int huntTemp = 0;
int huntSuccess = 0;
char huntChoice;
int encounterFood = 0;
int encounterWood = 0;
int encounterBullets = 0;
int encounterMedicine = 0;
int encounterHurt = 0;
unsigned int encounterChoice = 0;
int hurt = 0;
int health = 3;
int healthMax = 3;
int days = 1;
char action = '0';
char pause = '1';
char classChoice;
char mainChoice;
bool clown = true;
int clownHealth = 5;
char clownChoice;
int yourShot = 0;
int clownShot = 0;
string place;
//Food 1 per day per person. Can expand to include more people.
//Fuel 1 per day, takes that much to stay warm even if fewer people
//Medicine used one per wound
//Bullets 1 to hunt, though can spend more to increase chance of success.
//Days how many days that they have survied.
//Health, everyone starts with three health. Good, okay, bad, dead.
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;
while (health > 0){
cout << "\nDay: " << days;
cout << "\nFood: " << food
<< "\nWood: " << wood
<< "\nMedicine: " << medicine
<< "\nBullets: " << bullets
<< "\nHealth: " << health
<< "\nMoney: " << money << endl;
if (food >= 1){
food--;
}
if (wood >= 1){
wood--;
}
if (food <= 0){
health--;
cout << "Health lost due to lack of food" << endl;
}
if (health < healthMax && medicine > 0){
health++;
medicine--;
cout << "Health pack used to heal your character\nHealth : " << health << endl;
}
action = '0';
cout << "\n1: Find food" << endl;
cout << "What's your action? ";
cin >> action;
cout << endl;
if (action == '1'){
//
//Section for random sites to search.
//
//
randNumber = rand() % 4;
description = "";
//Maybe + days at the end, and subtract some, so that they eventually run out of places to check.
if (randNumber >= 0 && randNumber < 2) {
place = "supermarket";
foodTemp = (rand() % 4) + 1;
woodTemp = (rand() % 2) + 0;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 1;
moneyTemp = (rand() % 5) + 5;
}
if (randNumber >= 2 && randNumber < 4) {
place = "boat house";
foodTemp = (rand() % 2) + 1;
woodTemp = (rand() % 4) + 1;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 0;
moneyTemp = (rand() % 3) + 0;
}
cout << "You have come to the " << place << "." << endl;
cout << description << endl;
food += foodTemp;
wood += woodTemp;
bullets += bulletsTemp;
medicine += medicineTemp;
money += moneyTemp;
if (foodTemp > 0)
cout << "You have found " << foodTemp << " food." << endl;
if (woodTemp > 0)
cout << "You have found " << woodTemp << " wood." << endl;
if (medicineTemp > 0)
cout << "You have found " << medicineTemp << " medicine." << endl;
if (bulletsTemp > 0)
cout << "You have found " << bulletsTemp << " bullets." << endl;
if (moneyTemp > 0)
cout << "You have found " << moneyTemp << " money." << endl;
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
<< " Health: " << health << " Money: " << money << endl;
//End of search rooms.
}
//Random encounter chance to see if they can gain additional items.
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
//Option to attack clown
//
//
}
//End of random encounter from the clown.
//Pause mechanic to prevent the game from cycling.
// pause = 'b';
// while (pause != 'a'){
// cout << "\nEnter a to continue: ";
// cin >> pause;
// }
//End of game message
cout << endl;
if (days == 100){
cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
}
//Add day at end of while loop.
days++;
}
cout << "You have died after " << days << " days" << endl;
}
From another Stack Overflow question...
When an error occurs when reading from a stream, an error flag gets
set and no more reading is possible until you clear the error flags.
That's why you get an infinite loop.
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

nested if statement C++

I tried to write Nested if condition statement to calculate salary Raise in three condition, such as full-time, 2 part-time, or temporary. However, the result of salary Raise cannot be calculated. Are there any logic problems here. don't know where the mistakes are. Please help. Thank you for your comment.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char employmentStatus;
float performanceScore, salaryRaise = 0.0;
double fullTimeSalary = 10000;
double partTimeSalary = 8000;
double tempSalary = 5000;
double rate;
double bonus =500;
cout << "What is your employment status?" << endl;
cout << "Enter 1 (full-time), 2 (part-time), or 3 (temporary)"<< endl;
cin >> employmentStatus;
cout << "Now enter your performance score" << endl;
cin >> performanceScore;
cout << endl;
cout << fixed << showpoint << setprecision(2);
if (employmentStatus == 1)
{
if(performanceScore >= 8)
{
rate = 0.04;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.025;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else
{
salaryRaise = fullTimeSalary;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
}
else if (employmentStatus == 2)
{
if (performanceScore >= 8)
{
rate = 0.03;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.015;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 6 )
{
salaryRaise = partTimeSalary
}
}
else if (employmentStatus == 3)
{
salaryRaise = tempSalary
}
else
{
cout << " No result" << endl;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
system("pause");
return 0;
}
Your problems vary from logic to syntax.
Full code after my fix:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char employmentStatus;
float performanceScore, salaryRaise = 0.0;
double fullTimeSalary = 10000;
double partTimeSalary = 8000;
double tempSalary = 5000;
double rate;
double bonus =500;
cout << "What is your employment status?" << endl;
cout << "Enter 1 (full-time), 2 (part-time), or 3 (temporary)"<< endl;
cin >> employmentStatus;
cout << "Now enter your performance score" << endl;
cin >> performanceScore;
cout << endl;
cout << fixed << showpoint << setprecision(2);
if (employmentStatus == '1')
{
if(performanceScore >= 8)
{
rate = 0.04;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.025;
salaryRaise = fullTimeSalary * (1 + rate) + bonus;
}
else
{
salaryRaise = fullTimeSalary;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
}
else if (employmentStatus == '2')
{
if (performanceScore >= 8)
{
rate = 0.03;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 8 && performanceScore >= 6)
{
rate = 0.015;
salaryRaise = partTimeSalary + (salaryRaise*rate);
}
if (performanceScore < 6 )
{
salaryRaise = partTimeSalary;
}
}
else if (employmentStatus == '3')
{
salaryRaise = tempSalary;
}
else
{
cout << " No result" << endl;
return 0;
}
cout << "Your salary raise is: $" << salaryRaise << endl;
return 0;
}
Problems detected and explained solutions:
Syntax: There are couple of semi colons missing, you should debug this yourself compiler tells you where exactly.
Logic: You were doing this if (employmentStatus == 1) instead of if (employmentStatus == '1'), this not a problem on syntax level since C++ does implicit conversion of char to its ASCII code please see my answer on this for better explanation.
Syntax: system("pause") look at this, this and this. Just drop it.
Logic: If there are no results you should quit don't go further and display the raise, hence you have to add return 0; in the last condition.

the x should be =28.24778761 but i get 28

I just started learning c++
In this program i try two categorize two resistors based on their values
but at the end i cant print out correctly the x but only the part before ,
for example i tried r1=0 r2=50 r3=100 r4=60 V=9 n=4 1st value=55 2nd=56 3rd=52 4th=57 x should be 56*57/(56+57)=28.24778761 but i only get 28 why?
#include <iostream>
using namespace std;
int main()
{
int n;
float V, TOTAL1, TOTAL2, y;
int r1, r2, r3, r4, i;
cout << "Give r1: "; // Ask for resistors.
cin >> r1;
cout << "Give r2: ";
cin >> r2;
cout << "Give r3: ";
cin >> r3;
cout << "Give r4: ";
cin >> r4;
cout << "Give voltage: ";
cin >> V;
cout << "Give number of resistors: ";
cin >> n;
int a, b; // Ccount the number on its category.
int m;
m = 0;
a = 0;
b = 0;
y = 0;
TOTAL2 = 0;
for(i = 1; i < n + 1; i++)
{
y = TOTAL2 + y; // Calculate the as they are in series
float value;
m = m + 1;
cout << "\n Give resistance: ";
cin >> value;
if((value >= r1) && (value >= r2) && (value <= r3) && (value <= r4))
{
if(m % 2>0)
{
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1; // If they are in the first category they are connected in series
}
else
{
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value;
}
}
else if((value >= r1) && (value <= r2)){
cout << "It belongs to the first";
a = a + 1;
TOTAL1 = value + TOTAL1;
}
else if((value >= r3) && (value <= r4)) {
cout << "It belongs to the second";
b = b + 1;
TOTAL2 = 1 / value + 1 / TOTAL2;
}
}
long double x;
x = 1 / y;
cout << "\n The first category has: " << a;
cout << "\n The second category has: " << b;
cout << "\n The total resistance of the first category is: " << TOTAL1;
cout << "\n The total resistance of the second category is: " << x;
return 0;
}
The variable y is only updated at the top of the loop, so the last update is lost. So y contains 1/28 (the first value), and when you take its reciprocal, you get 28 exactly.

Compute tan(x) to be infinity in C++

#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
double cosin_value( double value );
double sin_value( double value );
double big_degree( double value );
double big_radian( double value );
double x;
double value;
double degree;
double radian;
const double PI = 3.14159;
char choice;
char yes;
int main()
{
cout << "Please enter an angle value => ";
cin >> value;
cout << "Is the angle in Degree or Radian?" << endl;
cout << "\t" << "Type D if it is in Degree" << endl;
cout << "\t" << "Type R if it is in Radian" << endl;
cout << "Your response => ";
cin >> choice; //degree or radian?
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
if (choice == 'D' || choice == 'd')
{
big_degree (value);
cout << " " << "sin(x) = " << "\t" << sin_value(degree) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(degree) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(degree) / cosin_value(degree) << endl;
}
else if (choice == 'R' || choice == 'r')
{
big_radian (value);
cout << " " << "sin(x) = " << "\t" << sin_value(radian) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(radian) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(radian) / cosin_value(radian) << endl;
}
return 0;
}
// Sine,cosine functions
// angle -360<value<360
double sin_value( double value )
{
int count=1;
double sine, num, dem, sign, term;
sine = 0;
sign = 1;
num = value;
dem = count;
while ( count <= 20 )
{
term = ( num / dem );
sine = sine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (sine);
}
double cosin_value( double value )
{
int count = 0;
double cosine, num, dem, sign, term;
cosine = 0;
sign = 1;
num = 1;
dem = 1;
while ( count <= 20 )
{
term = ( num / dem );
cosine = cosine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (cosine);
}
double big_degree( double value )
{
int result;
const int angle = 360;
if (value >= 360 || value <= -360)
{
result = value / angle;
degree = ( value - ( result * angle ) ) * PI / 180;
}
else
{
degree = ( value * PI ) / 180;
}
return (degree);
}
double big_radian( double value )
{
int result;
if (value >= 2 * PI || value <= -2 * PI)
{
result = value / ( 2 * PI );
radian = ( value - ( result* 2 * PI ) );
}
else
{
radian = value;
}
return (radian);
}
I have few problems here:
How can the program shows tan(x) is infinity when I input a value 90 degree or 1.5708 radian? When I input 90 degree, it gave me an output of 0.0000013268 instead of 0 for cos(x).
I tried to put in this command in my cosin function where If cos(x)<0.00001, set it to zero, it worked for 90 degree but for other values like 2.3145 radian, cos(x) value is 0 instead of -0.677013.
I appreciate your guides!
Use epsilon value just like you mentioned in question #2.
Use an absolute value of cos(x) like abs(cos(x)) in your if statement. .
You can also represent infinity with double or float. Check this link.
http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
More importantly, you might want to read this article called "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You will notice that each step of your floating point operations will accumulate errors in calculation.

Compute cos(x) to 0 when x is 90 degree or pi/2 radian in C++

# include <iostream>
# include <math.h>
# include <cstdlib>
using namespace std;
double cosin_value( double value);
double sin_value( double value);
double big_degree (double value);
double big_radian (double value);
double x;
double value;
double degree;
double radian;
const double PI = 3.14159;
char choice;
char yes ;
int main()
{
cout << "Please enter an angle value => ";
cin >> value;
cout << "Is the angle in Degree or Radian?" << endl;
cout << "\t" << "Type D if it is in Degree" << endl;
cout << "\t" << "Type R if it is in Radian" << endl;
cout << "Your response => ";
cin >> choice; //degree or radian?
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
if (choice == 'D' || choice == 'd')
{
big_degree (value);
cout << " " << "sin(x) = " << "\t" << sin_value(degree) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(degree) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(degree)/cosin_value(degree) << endl;
}
else if (choice == 'R' || choice == 'r')
{
cout << " " << "sin(x) = " << "\t" << sin_value(radian) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(radian) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(radian)/cosin_value(radian) << endl;
}
return 0;
}
// Sine,cosine functions
// angle -360<value<360
double sin_value( double value)
{
int count=1;
double sine, num, dem, sign, term;
sine=0;
sign = 1;
num = value;
dem = count;
while ( count <= 20 )
{
term = (num/dem);
sine = sine + term*sign;
num = num*value*value;
count = count + 2;
dem = dem * count * (count-1);
sign = -sign;
}
return (sine);
}
double cosin_value( double value)
{
int count=0;
double cosine, num, dem, sign, term;
cosine=0;
sign = 1;
num = 1;
dem = 1;
while ( count <= 20 )
{
term = (num/dem);
cosine = cosine + term*sign;
num = num*value*value;
count = count + 2;
dem = dem * count * (count-1);
sign = -sign;
}
return (cosine);
}
double big_degree (double value)
{
int result;
const int angle=360;
if (value >= 360 || value <= -360)
{
result=value/angle;
degree=(value-(result* angle))*PI/180;
}
else
{
degree = (value*PI)/180;
}
return (degree);
}
double big_radian (double value)
{
int result;
if (value >= 2*PI || value <= -2*PI)
{
result=value/(2*PI);
radian=(value-(result* 2*PI));
}
else
{
radian = value;
}
return (radian);
}
Hi, this is basically the whole program I wrote for calculating trigonometric value using the extent knowledge I knew in C++ as a beginner. For a better view, you can refer to this link regarding my code above :codepad.org
the line starting from line 114 onwards are the function that I created. There's a problem there where how can I compute my cosx to be 0 when the value is 90 degree or pi/2 radian?
since the program will still calculate tanx for me even the value is 90 degree.
Let's say by giving value 90 degree to the program, it will give me the value of 0.0000013268 instead of 0.000000
sorry, since I'm just a beginner, the code will look weird for you guys.
I appreciate your guides!
double big_degree(double value) means when the value is >= 360 or <= -360*
I do not allocate any heap space in my brain for digits of pi, but I do remember that atan(1) == pi / 4.
Change your PI constant like so:
const double PI = atan(1) * 4;
Taking your code, making that change, I get
Please enter an angle value => 90
Is the angle in Degree or Radian?
Type D if it is in Degree
Type R if it is in Radian
Your response => d
sin(x) = 1.0000000000
cos(x) = 0.0000000000
tan(x) = 15555226593901466.0000000000
const double PI = 3.14159;
The more precise you make this definition, the more close to 0 will the value of cos PI/2 get!
If you get the input itself in radians, there also the same criteria applies.
The problem isn't your code. The input you have given is not sufficiently accurate. Calculate the proper value of pi/2, and you will get a sufficiently accurate value.Also, if you want to round off the values you can use#rounded off value=Math.Round(#old value, 4)
My soulution:
double mySin(double x)
{
if (fmod(x, std::numbers::pi) == 0)
return 0;
return sin(fmod(x, std::numbers::pi * 2.0));
}
double myCos(double x) { return mySin(x + std::numbers::pi / 2); }
myCos(std::numbers::pi / 2) == 0 //True
myCos(std::numbers::pi) == -1 //True
myCos(std::numbers::pi * 2) == 1 //True