I made a program that calculates the area of a circle. You have the option to enter a diameter or a radius. After you select one of them, you enter the value. Then it tells you what you entered and gives you the answer. But the answer isn't correct. For example, I enter 'r' then type '3' it gives me:
This is a calculator that calculates the area of a circle.
To get started, type 'd' (no quotes or caps) to enter a diamater.
Type 'r' (no quotes or caps) to enter a radius.
r
You chose radius, now please enter a number.
3
3 * 2 * 3.14 = 40828.1
It doesn't look right, as you can see. Perhaps C++'s Pi variable is outdated?
#include <iostream>
#include <math.h> // Importing math.h so I can use the M_PI variable.
using namespace std;
int main() {
char choice;
float result = 0.0; // Set to zero to init and stop the IDE from complaining.
float number = 0.0;
cout << "This is a calculator that calculates the area of a circle." << endl;
cout << "To get started, type 'd' (no quotes or caps) to enter a diamater." << endl;
cout << "Type 'r' (no quotes or caps) to enter a radius." << endl;
cin >> choice;
choice = tolower(choice); // Making it lower case so it's easier for compiler to recoginize.
switch (choice) {
case 'r':
cout << "You chose radius, now please enter a number." << endl;
cin >> number;
result = choice*choice*M_PI;
break;
case 'd':
cout << "You chose radius, now please enter a number." << endl;
cin >> number;
result = choice*M_PI;
break;
default:
cout << "You entered an invalid character. Please only enter 'r' or 'd' (no quotes or caps)" << endl;
break;
}
if (choice == 'r')
{
cout << number << " * 2 * 3.14 = " << result << endl;
}
else if (choice == 'd') {
cout << number << " * 3.14 = " << result << endl;
}
else {
cout << "Nothing here cause you didn't do simple stuff correctly..." << endl;
}
return 0;
}
Since you are new couple things you need to remember:
switch case and if/else statement are pretty similar, therefore you don't need to use them both at the same time on same task.
When the program runs the user inputs a value either r or d , that value get passed to the choice variable. The switch case compares its own cases to the choice value and if both value are equal, it will run that case code block and if they are not it will run the default code.
Now inside the case, you are asking for the radius, once you get the radius,
result = number * number * M_PI;
OR
result = pow(number,2.0) * M_PI;
And also there is a big difference between cout<<"2*3"; and cout<<2*3;
The first example will display 2*3 into your screen.
The second example will display the result of 2*3 into the screen
6, the reason you it calculates because there is not quotation mark around it
Hope that helps...
Shoulr calculation of result use choise???
Looks like you have a typo. Replace choise woth number in the
result = choice*choice*M_PI;
And in the
result = choice*M_PI;
Using choise in calculation actually uses its ASCII code. This explains the big values that you get in the result.
result = choice*choice*M_PI;
this should be
result = number * number * M_PI;
also you are printing
* 2 * 3.14 =
should be
^ 2 * 3.14 =
Related
I'm doing an assignment and while I have it pretty much entirely done, I've run into a problem. The program is supposed to find the square root of a number the user inputs using the Babylonian square root algorithm. I was given an example output, and mine does not quite match. Also if you see any more issues please, give me a heads up! Especially if it's about the do while loop (it was the only solution I could get that stopped an infinite loop issue I was having).
#include <ios>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
std::cout << std::fixed << std::setprecision(4);
//variables
int input;
double guess, r, check, test;
//input
cout << "Enter a number and I will apply the\n";
cout << "Babylonian square root algorithm until\n";
cout << "I am within .001 of the correct answer\n";
cin >> input;
cout << "You input " << input << "\n";
//calculate
guess = input / 2;
do {
test = guess;
r = input / guess;
guess = (guess + r) / 2;
cout << "\nguessing " << guess;
} while (guess != test); //while end
//check
check = guess * guess;
cout << "\nThe Babylons algorithm gives " << guess;
cout << "\nChecking: " << guess << " * " << guess << " = " << check << "\n";
} //main end
**Example output:**
Enter a number and I will apply the Babylonian square root algorithm
until I am withing .001 of the correct answer.
151
You entered 151
guessing 38.75
guessing 21.3234
guessing 14.2024
guessing 12.4172
guessing 12.2889
The Babylons algorithm gives 12.2889
Checking: 12.2889 * 12.2889 = 151.016
Press any key to continue . . .
**My Output:**
Enter a number and I will apply the
Babylonian square root algorithm until
I am within .001 of the correct answer
151
You input 151
guessing 38.5067
guessing 21.2140
guessing 14.1660
guessing 12.4127
guessing 12.2888
guessing 12.2882
guessing 12.2882
guessing 12.2882
The Babylons algorithm gives 12.2882
Checking: 12.2882 * 12.2882 = 151.0000
Change the type of input from int to double:
double input;
which changes initial value of guess = input / 2 from floor(151/2) = 75.0 to 75.5 for the expected sequence of values. Alternatively, cast the enumerator input to a double in the expression with:
guess = (double) input / 2;
or more elegantly via implicit type conversion by using floating point value as the divisor at suggested by #AlanBirtles:
guess = input / 2.0;
To fix the loop test:
#include <math.h>
...
do {
...
} while(fabs(test - guest) > 0.001);
So I am making this as a homework assignment. I understand that there are so many ways that this code could be more efficient and accurate but this is the way my professor wants it done.
I am having problems with the loop. When I ask for the square root of 67 it does find it but it loops the correct answer 3 times.
Enter a value to be square rooted:
67
33.5
guess = 17.75
guess = 10.7623
guess = 8.49387
guess = 8.19096
guess = 8.18535
guess = 8.18535
guess = 8.18535
The program took 7 guess to find an estimation.
When I try to find the square root of 5 it finds it but continues to loop indefinitely
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess1 = squarenumber/2;
cout << guess1 << endl;
do
{
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
guess1 = guess2;
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
I think that what you are missing is a proper exit condition.
Your code is written to loop indefinitely until the guess is "perfect".
You should have an exit condition checking if current guess is the same as previous guess, which obviously means that you won't do any better.
Here is my suggestion based on your code :
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess2 = guess1 = squarenumber/2;
cout << guess1 << endl;
const double epsilon = squarenumber * 1E-6;
do
{
guess1 = guess2;
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber && fabs(guess2-guess1) > epsilon);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
Mickaël C. Guimarães's answer is basically correct, check for an episolon value (absolute difference from the correct answer and your answer). But the "(guess2 * guess2) > squarenumber" should be dropped completely. That's because the value could in theory overshoot and be too low. The algorithm actually goes upwards if the value is too low. e.g. if you want SQRT(25) and your "guess1" prediction is way too low at 2, then guess2 would equal
(2 - (((2 * 2) - 25)/(2* 2))) = 7.25;
And on the next iteration then falls to 6.725624, so heads in the right direction. Low values actually get boosted up and eventually approach the target. By stopping if the value drops below the true SQRT then you might get "false positives" where too low values are accepted as accurate enough.
The times when the system got "stuck" were basically like the story Acchiles and the Tortoise. At each step, the system was dividing the remaining distance to go by some amount, but the change was therefore smaller each step, and could in theory never converge on the exact value, therefore you decide how much accuracy you want so that it finishes in a set time.
Additionally, the issue where the system seemed to take too many steps to converge is because floating point numbers are stored in higher precision, but cout has limited display precision. You can control that by sending setting values to cout before the print commands:
std::cout << std::fixed; // force all values to show to the same decimals
std::cout << std::setprecision(6); // set how many places to show
These code can be streamed to cout in one command before the value to print as well:
std::cout << std::fixed << std::setprecision(6) << "guess = " << guess2 << endl;
I added comments to the code, do I have a compiler issues? I can't figure it out, I tried looking on google and the book but I cant figure out why the first half of code only accepts the input with space between the number and unit and second code accepts the number and unit together.
I'm using code blocks. So far I tried closing it and opening it again.
int main(){
constexpr double dollar_to_euro = 0.91;
constexpr double dollar_to_yen = 117.07;
constexpr double dollar_to_pounds = 0.70;
double sum = 1;
char curr = '\0'; // tried replacing '\0' with '0' and ' '
cout << "Please enter sum, followed by currency for conversion.\n"
<< "U for dollar, E for euro, Y for yen and P for pounds.\n";
cin >> sum >> curr; // This is my issue, it does not want to accept "sumcurr" together, it only accepts it if theres space in between
// yet on the second code for inches or centimeters it does accept them being together. Look down.
// For example entering "5 E" works, yet "5E" does not work.
if(curr=='E')
cout << "The amount " << sum << " euro is " << sum/dollar_to_euro << " dollars\n";
else
cout << "GOD DAMMIT !!!!\n";
constexpr double cm_per_inch = 2.54;
double len = 1;
char unit = '\0';
cout << "Please enter length followed by unit.\n";
cin >> len >> unit; // Over here it works, this is an example from a book. Entering "5i" works.
if(unit=='i')
cout << len << " in == " << cm_per_inch*len << "cm.\n";
else
cout << "Wrong input !\n";
}
The problem here is that E/e is valid in a floating point number but 5E/5e is not a valid floating point number as you need a value after the E/e. So when you enter 5e the input for sum fails because of the invalid syntax where 5e0 would work. If you use anything other than E/e then it will work like your second example.
For more information on the format of floating point numbers see: Cppreference floating point literal
Hello i am a student so i wanted to say sorry in case my writing is tiring, feel free to correct me .
i am having the following problem i am trying to assign an enum int value to another double variable to make one multiplication.
so the variable costOfRoom should take the value D or T or S which belong to an enum. (D=200 ,T=150,S=110)
this must be done by the user .
But cant find any way , i tried to make the second variable a string type but its not working again. it will just take the chars normally as a string would do :(
Also tried cin >> type_Ofroom costofroom ;
but i think that this is used in Java??
Searched the forum also haven't any similar answer :(
The program runs fine it doesn't have any compiling errors :)
Thanks for your time
/* build a software system which will allow a hotel receptionist,
to enter in bookings for guests who come to the desk.
The system should display the room options as:
Room Price Code
---------------------------------------------------------------
Deluxe Room £200 D
Twin Room £150 T
Single £110 S
The receptionist should be prompted to enter in the room type and the number of
nights a guest wishes to stay for and then calculate the amount
they need to pay.
*/
// solution
#include <iostream>
using namespace std;
int main() {
// decleration of variables
double number_OfDays = 0, Totalcost = 0, costofroom = 0;
enum type_Ofroom { D = 200, T = 150, S = 150 };
cout << "enter the type of the room " << endl << endl;
//input of room type
cin >> costofroom; // **here is the problem** i am trying to give the
// values of the enum varaiable
// it should have D or T or S but i cant make it
cout << "enter the number of the days " << endl << endl;
//input of days
cin >> number_OfDays;
// calculation
Totalcost = costofroom * number_OfDays;
// result
cout << "the costumer has to pay " << Totalcost << " pounds" << endl << endl;
return 0;
}
You can read into a double, and then check against your enum values:
//input of room type
while (1)
{
cin >> costofroom;
if (costofroom == 0.0)
costofroom = D;
else if (costofroom == 1.0)
costofroom = T;
else if (costofroom == 2.0)
costofroom = S;
else
{
cout << "You didn't enter a valid option" << endl;
continue;
}
break;
}
However, it would be better to read into an int, and then set your double afterward.
double costofroom;
int option;
...
//input of room type
while (1)
{
cin >> option;
if (option == 0)
costofroom = D;
else if (option == 1)
costofroom = T;
else if (option == 2)
costofroom = S;
else
{
cout << "You didn't enter a valid option" << endl;
continue;
}
break;
}
The user can only input characters. cin will convert groupings of numbers to an int (e.g. 123) or or double (e.g. 123.5). It will also handle non-numeric groupings to std::strings (e.g. hello) or individual characters (e.g. c).
Once you have the user's input, you can convert them to your enum. You can use if statements, case statements or some type of table look up to do this.
This was an exercise from Principles and Practice Using C++ to make a basic currency converter using if checks then to remake it with switches. Everything runs pretty good except or my middle switch. It doesn't seem to work like the rest of the program. Every other one is fine with me entering in data like 111y, 111p but when working with euros it NEEDS a whitespace or else it will go to the default switch. I did a break point and currency is not being set to e or E and it's only with the euros!
I hope it isn't anything too silly, but it's got me confused Bjarne doesn't explain this one :P I don't have #include iostream in the code because it's all handled with *std_lib_facilities* Just wanted to say that before someone points it out XD
#include "std_lib_facilities.h"
using namespace std;
int main()
{
double dollar = 0;
char currency = ' ';
const double yen = 0.010;
const double euro = 1.31;
const double pound = 0.65;
double sum = 0;
cout << "Please enter amount and Y for yen or E for Euro or P for pound.\n";
cin >> dollar >> currency;
switch(currency)
{
case 'Y': case'y':
{
sum = dollar * yen;
cout << dollar << " is equal to " << sum << " yen.\n";
break;
}
case 'E': case'e':
{
sum = dollar * euro;
cout << dollar << " is equal to " << sum << " euro.\n";
break;
}
case 'P': case'p':
{
sum = dollar * yen;
cout << dollar << " is equal to " << sum << " pound.\n";
break;
}
default:
cout << "Wrong values...\n";
break;
}
keep_window_open();
return 0;
}
Since dollar is a double, the E or e gets interpreted as part of the exponent of the number (as in 2e-2) when you extract it. Since there are no digits after it, the extraction does not complete and cin goes into the fail state. The read of currency is then skipped, never changing it from the initial value of ' '. When you enter a space, the extraction of dollar ends at the space and currency is read as expected.
To fix it, you could try several things. You could require a space between the amount and the currency indicator. You could read it in as a string and attempt to parse it yourself. You could pick a different symbol for euros.
In any case, you should check the state of the cin after you're done reading from it.