I'm trying to create a simple change sorter program, everything is functioning properly expect for the part that's suppose to detect quarters.
Example of current output:
The amount you entered is: 52.50
You have this many Fifty dollars: 1
You have this many Ten dollars: 0
You have this many One: 2
You have this many Quarters: 0
Desired output:
The amount you entered is: 52.50
You have this many Fifty dollars: 1
You have this many Ten dollars: 0
You have this many One: 2
You have this many Quarters: 2
Code:
#include <iostream>
using namespace std;
const int FIFTY = 50;
const int TEN = 10;
const int ONE = 1;
const double QUARTER = 0.25;
int _tmain(int argc, _TCHAR* argv[])
{
int change;
cout << "Enter the amount of money in your wallet: ";
cin >> change;
cout << endl;
cout << "The amount you entered is: " << change << endl;
cout << "The number of Fifty dollars to be returned is: " << change / FIFTY << endl;
change = change % FIFTY;
//
cout << "The number of Ten dollars to be returned is: " << change / TEN << endl;
change = change % TEN;
//
cout << "The number of One dollars to be returned is: " << change / ONE << endl;
change = change % ONE;
//
cout << "The number of Quarters to be returned is: " << change / QUARTER << endl;
change = change % QUARTER;
return 0;
}
The 2 errors I'm getting are:
Error 1 error C2297: '%' : illegal, right operand has type 'double'
Error2 IntelliSense: expression must have integral or unscoped enum type
Your change variable is an int type, so it won't store 52.50 at all.
It will read the 52 then stop.
On top of that, you can't use floating point values in the % operator.
I would suggest reading the value as a double, multiplying it by a hundred, perhaps adding a small delta (like 0.001) so as to avoid potential floating point precision problems, then placing that into an int. In other words, make it an integral number of cents.
Then use the int for doing the calculations.
Related
I am trying to solve the first problem of this collection
To find and display the value of Pi till the Nth digit (taken as user input limited by some maximum value, my guess the maximum number of decimal places the biggest ds can hold which is long double i guess?)
Below is a snippet of my attempt.
//declarations
typedef numeric_limits< long double > db;
int MAX = db::digits10;
int N = 0; //digit allowance
long double pi_val = M_PI;
string string_pi;
//user input
while(1){
cout << "Enter a value of n < or = " << MAX << endl;
cin >> N;
if(N>18){cout << "Lesser please" << endl;}
else
break;
}
//outputs
cout << "Pi till the " << N << " digit is: ";
cout << setprecision(N+1) << fixed << pi_val << endl;
string_pi = to_string((long double)pi_val * pow(10, N));
cout << string_pi << endl;
cout << "The Nth digit of pi is: " << string_pi[N] << endl;
Ps I am aware that more novel ways exist to go about the problem but since I am an extreme beginner at cpp, I'd attain a better sense of achievement by making my idea work.
Now the problem, it displays the Nth digit correctly but the output of Pi till the Nth value always gets rounded off despite the 'fixed' and 'setprecision()' so I had to display an extra digit to tally with the latter output
How can I fix this problem, if possible without changing the main logic I have used
Thank you
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "\n* This is a program that counts integers you enter as *"
<< "\n* even, odd or zero and positve or negative *"
<< "\n* It classifies 20 numbers or use 99999 to exit early *"
<< "\n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "\n\nPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "\n\t\t or enter number 99999 to exit early. \n\n"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "\n\n\tPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
I am debugging this program. There were originally 6 errors in the program. I've found four of them as they were syntax errors. The compiler doesn't show any error but the program isn't working either.
The program is supposed to store 20 numbers and in the end tell you how many of them were even, odd, zero, negative, and positive. I am just a beginner in C++. I have tried every possible way to solve it from my side but I cannot get it to work. I have looked up every code and syntax on Google why it works that way but found no help. Any help here would be highly appreciated.
If you enable warnings when you compile then the compiler will helpfully point out certain mistakes in your code, and if it's in a good mood it may even suggest a solution:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
Always compile with warnings enabled (e.g. gcc -Wall ...) - it will save you a lot of time and debugging effort in the long run.
This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
Hi guys I'm rather new to programming and working my way through Stroustrup's "Programming, Principles and Practice Using C++" and I've come to a complete standstill at the end of Chapter 3 with an exercise asking you to write a piece of code that does a number of calculations involving 2 numbers which includes finding the ratio of the numbers. Unfortunately this hasn't been covered at all in the book and I'm tearing my hair out trying to figure it out by myself, only able to find examples of code way to advanced for my small little brain.
The code I have at the moment is:
double ratio;
if (val2 > val1)
ratio = (val2 / val1);
if (val2 < val1)
ratio = (val1 / val2);
cout << "The ratio of " << val1 << " and " << val2 << " is 1:" << ratio << '\n';
which works fine for numbers that equate to a whole ratio (e.g. 100 and 25) however despite me setting the variable "ratio" as a double it removes any decimals from the answer in cases of non whole number ratios. Can anyone tell me where I'm going wrong?
When dividing integers the result is integer (integer arithmetics is used):
11 / 2 == 5
11 % 2 == 1 /* remainder */
and when dividing floating point values the result is floating point as well:
11.0 / 2 == 5.5
11 / 2.0 == 5.5
((double) 11) / 2 == 5.5
In your case
double ratio = (val2 / val1);
you have an integer division and only after the disvison performed the outcome of it is cast to double. You can either declare val2 and val1 as double:
double val1;
double val2;
or cast at least one argument of the ratio to double:
double ratio = ((double)val2) / val1;
The fact that result type is double doesn't matter if the original division is performed on integral types (truncating the decimal part).
So to solve your problem, either:
Use a floating point type for the input numbers as well
Cast one of the numbers to a floating point type before division
I did the whole problem from Stroustrup's "Programming, Principles and Practice Using C++. Here is the codes although no comments.
int main()
{
/** --------Numbers-----*/
int val1;
int val2;
double largest; //I'll store here the largest value
double smallest; //I'll store here the smallest value
cout<< " Enter two Numbers to play with\n";
while(cin>> val1>>val2){
if(val1<val2){
cout<< "smallest: "<<val1<<endl;
cout<< "largest: "<<val2<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val2;
smallest=val1;}
if(val1>val2){
cout<< "smallest: "<<val2<<endl;
cout<< "largest: "<<val1<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val1;
smallest=val2;}
int their_sum=val1+val2;
int their_product=val1*val2;
int their_diff=val1-val2;
double ratio1;
ratio1=largest/smallest;
cout<<"Sum: "<<their_sum<<endl;
cout<<"Difference: "<<their_diff<<endl;
cout<<"Product: "<<their_product<<endl;
cout<<"Ratio: "<<ratio1;
}
return 0;
}
There is nothing new in this code, everything was covered in the previous chapters.
If at all you need ratio of two numbers say a,b in the form of n:m (where n>=1) then simply find the GCD(a,b) and divide a,b with this result.
eg:
a=4,b=6;
GCD(a,b)=2;
n=4/2=>2
m=6/2=>3
so ratio of 4 and 6 is 2:3
#include<iostream>
using namespace std;
class Test
{
public:
void check()
{
int x,y;
cout<<"Enter 1st number";
cin>>x;
cout<<"Enter 2nd number";
cin>>y;
int a;
int d= gcd(x,y);
cout<< x/d << " : " << y / d << endl;
}
int gcd(int x, int y) // 14, 21
{
int d;
if(y>x)
{
y=x+y;
x=y-x;
y=y-x;
}
for(int i=1; i<=y; i++)
{
if(x%i==0 && y%i==0 )
{
d=i;
}
}
return d;
}
};
int main()
{
Test t;
t.check();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val1,val2;
cout << " Enter two integer values followed by enter" << endl << endl;
cin >> val1;
cin >> val2;
if(val1 < val2) // To determine which value is larger and which one is smaller
{
cout << val1 << " is smaller than" << val2 << endl << endl << "And" << val2 << " is larger than " << val1 << endl<<endl;
}
enter code here
else if( val2 < val1)
{
cout<<val2 <<" is smaller than"<< val1<<endl<<endl<<"And"<< val1 << " is larger than "<< val2<< endl << endl;
}
cout << "The sum of "<< val1<<" and "<<val2<<" is "<< val1+val2<<endl<<endl;
// diplaying the sum of the two numbers
enter code here
cout << " The difference between "<<val1<< " and "<<val2<< " is " << val1-val2<<endl;
// displays the difference of val2 from val1
cout << " The difference between "<<val2<< " and "<<val1<< " is " << val2-val1<<endl;
// displays thr difference of val1 fromval2
enter code here
enter code here
cout << " The product of " <<val1<< " and " << val2<< " is " << val1*val2<< endl<<endl;
// displaying the product of val1 and val2
enter code here
enter code here
enter code here
// now to diplay the ratio of the two numbers
double ratio1;
cout << " The ratio of "<<val1<<" and "<<val2<<" is ";
if(val1 < val2)
{
ratio1= ((double)val2) /val1;
cout << ratio1;
}
else if(val1 > val2)
{
ratio1= ((double)val1) /val2;
cout << ratio1;
}
}
I get an error message that states "expected primary-expression ';' token" and it highlights my percentage formula. I have tried to rearrange my code, but it seems the problem is not in it.
const int TOTALSUITES = 120;
for (int floor = 10; floor <= 16; floor++) {
if ( floor != 13) {
do {
cout << "Please enter the number of suites occupied on the floor " << floor << ":";
cin >> numOccupied;
if ((numOccupied <0) || (numOccupied >20 )) {
goodChoice = false;
cout << "\n\t\t**ERROR" << numOccupied << " ***\n\n";
cout << "*** Choice must be from [0-20]***\n";
}
else {
goodChoice = true;
}
totalOccupied += numOccupied;
} while (!goodChoice);
}
}
percentage = (totalOccupied / TOTALSUITES) * 100% ;
cout << endl;
cout << "Hotel has " << TOTALSUITES << endl;
cout << "Number of occupied suites is " << totalOccupied << endl;
cout << "The percentage of occupied suites is " << percentage << endl;
system("pause");
return 0;
% used here is the modulo operator which is a binary operator...
so this is what you have to do...
percentage = (totalOccupied / TOTALSUITES)* 100;
//and then where you have cout percentage at that point...do this
cout<<"the percentage of occupied suites is"<<percentage<<"%";
100% is not 100 percent. 100% is trying to use the % operator in an incorrect manner. To multiply by 100% you just use 1 which is not needed as anything times 1 is itself.
percentage = (totalOccupied / TOTALSUITES) * 100% ;
This is not valid syntax. Change it to this.
percentage = (totalOccupied / TOTALSUITES);
Assuming your totalOccupied is not a float, you should probably do this as well:
percentage = (static_cast<float>(totalOccupied) / TOTALSUITES);
% is actually the modulus operator in C++, requiring two arguments.
100% is therefore not syntactically valid.
Assuming that you want % to stand-in for a "divide by 100" operator, the simplest thing to do in your case is to drop the 100% from your code.
Note that totalOccupied / TOTALSUITES will be carried out in integer arithmetic if totalOccupied is also an int or unsigned. Fix that by promoting one of the arguments to a double, or pre-multiply the term with 1.0.
The question:
Giving change. Implement a program that directs a cashier how to give
change. The program has two inputs: the amount due and the amount
received from the customer. Display the dollars, quarters, dimes,
nickels, and pennies that the customer should receive in return.
What i have so far:
#include <iostream>
using namespace std;
int main()
{
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change % 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) % 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) % 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) % 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) % 1 << endl;
system("pause");
return 0;
}
I realize there are some other one of these answered but they may be to advanced to use in my code, what am i doing wrong?
What you want to do is the same as a cashier would do.
First ensure the change is represented as whole pennies.
Then provide enough dollars until the change remaining is less than a dollar. Then move on to quarters, then dimes, nickels and pennies.
So for the dollar case, pseudo-code would be:
dollars = change / 100 # get integral number of dollars
change = change % 100 # and reduce change-left-to-go accordingly
print dollars, " dollars"
It should then be a simple matter to apply that logic to the other coin types in order of reducing value.
There are several problems. The first is that you ask the user to input values, but don't specify what they are. If the user enters a number that's not in pennies, you're not going to get the value you expect. I expect this input should be in dollars. So, first, change change into:
change = int((amount_recieved - amount_due) * 100.0)
Next:
cout << "dollars: " << change % 100 << end;
Will return the remainder of dividing change by 100, which is not what you want. You simply want to divide dollars by 100. You also want to likely modify change to stop you having to repeat this math.
dollars = change / 100;
cout << "dollars: " << dollars << endl;
change -= dollars*100;
From there, the rest of the code should work as expected minus the % 100 parts. As others have mentioned in the comments to the question, your problem is arising from not thinking the math through first, not from doing anything inherently wrong with C++. This would have produced the wrong result in any language, including writing it down as math on a blackboard.
As others have mentioned, you are not doing the step required to get this working, and that is repeated subtraction. Yes, you subtracted the price from the amount given, and determined the dollars to give, but you failed to subtract out those dollars, giving you a new total to determine how many quarters.
Something like this (assuming you're working in pennies):
change_left = customer_payment - original_cost;
//...
number of dollars = change_left / 100;
change_left = change_left - (100 * number of dollars); <-- where is this?
Now how do you determine the number of quarters? You have a "running total" called change_left that is being reduced by the change you currently have given the customer. You repeat similar steps to get the number of quarters, then number of dimes, nickels, etc., i.e. divide by 25, then subtract out the number of quarters giving a new "change_left". Then repeat for 10 to get the dimes, 5 to get the number of nickels, etc.
So again, the problem isn't C++ -- the issue is that you are not thinking this out as a discrete series of steps that lead to a final goal.
#include <iostream>
using namespace std;
int main() {
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change / 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) / 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) / 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) / 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) / 1 << endl;
return 0;
}