I am novice at programming in C++. I want to write a program using while loop which displays the trigonometric table for sin, cos and Tan. It takes angles in degrees with a difference of 5 and displays the result. This it what I tried,
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int num;
cout<< "Angle Sin Cos Tan"<<endl;
cout<< "..........................."<<endl;
num=0;
while (num<=360)
{
cout <<setw(3)<<num<<" "
<<setw(3)<<setprecision(3)<<sin(num)<<" "
<<setw(3)<<setprecision(3)<<cos(num)<<" "
<<setw(5)<<setprecision(3)<<tan(num)<<endl;
num=num+5;
}
}
Unfortunately, I could not change radians into degrees in while loop and the display does not look promising even for radians. How can I resolve it ?
To convert degrees to radiant you have to multiply by pi and to divide by 180.0:
#define M_PI 3.14159265358979323846
int num = 0;
while (num<=360)
{
double numRad = num * M_PI/180.0;
std::cout <<std::setw(3)<<num<<" "
<<std::setprecision(3)<<std::fixed
<<std::setw(6)<< std::sin( numRad ) <<" "
<<std::setw(6)<< std::cos( numRad ) <<" ";
if ( num != 90 && num != 270 )
std::cout<<std::setw(6)<< std::tan( numRad ) <<std::endl;
else
std::cout<< "infinitely" <<std::endl;
num=num+5;
}
To use constant M_PI see How to use the PI constant in C++
To convert degrees to radians, use numRad = M_PI / 180.0 where M_PI should be a constant that holds the value od Pi. If you do not have such a constant defined in a header file, just define it yourself, like #define PI 3.14159265
The functions sin, cos and tan always require arguments in radians.
Related
For determining how many terms are required for the first time getting pi that begins with 3.14159 I wrote the following program that calculates terms as (pi = 4 - 4/3 + 4/5 - 4/7 + ...).
My problem is that I reached 146063 terms as the result but when I checked, there are many pis that begin similarly before that.
//piEstimation.cpp
//estima mathematical pi and detrmin when
//to get a value beganing with 3.14159
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
//initialize vars
double denominator{1.0};
double pi{0};
string piString;
double desiredPi;
int terms;
int firstDesiredTerm;
//format output floating point numbers to show 10 digits after
// decimal poin
cout << setprecision (10) <<fixed;
for (terms = 1; ; terms++){
if(0 == terms % 2){ //if term is even
pi -= 4/denominator;
}
else{ //if term is odd
pi += 4/denominator;
}
// draw table
cout << terms << "\t" << pi << endl;
//determin first time the pi begains with 3.14159
piString = to_string(pi).substr(0,7);
if(piString == "3.14159"){
firstDesiredTerm = terms;
desiredPi = pi;
break;
}
denominator += 2;
}//end for
cout << "The first time that pi value begans with 3.14159 "
<< "the number of terms are " << firstDesiredTerm << " and pi value is "<< desiredPi <<endl;
}//end main
A number x begins with 3.14159 if x >= 3.14159 && x < 3.1416. There is no need to use strings and compare characters. to_string has to use some kind of round operation. Without the string the algorithm finds the result after 136121 steps
#include <iostream>
#include <iomanip>
int main(){
//initialize vars
double denominator{1.0};
double pi{0};
double desiredPi;
int terms;
int firstDesiredTerm;
//format output floating point numbers to show 10 digits after
// decimal poin
std::cout << std::setprecision (20) << std::fixed;
for (terms = 1; ; terms++){
if(0 == terms % 2){ //if term is even
pi -= 4/denominator;
}
else{ //if term is odd
pi += 4/denominator;
}
// draw table
std::cout << terms << "\t" << pi << std::endl;
if(pi >= 3.14159 && pi < 3.1416){
firstDesiredTerm = terms;
desiredPi = pi;
break;
}
denominator += 2;
}//end for
std::cout << "The first time that pi value begans with 3.14159 "
<< "the number of terms are " << firstDesiredTerm
<< " and pi value is "<< desiredPi << std::endl;
}
Output:
The first time that pi value begans with 3.14159 the number of terms are 136121 and pi value is 3.14159999999478589672
Here you can see how to_string rounds the result:
#include <iostream>
#include <iomanip>
#include <string>
int main(){
std::cout << std::setprecision (20) << std::fixed;
std::cout << std::to_string(3.14159999999478589672) << '\n';
}
Output:
3.141600
You can read on cppreference
std::string to_string( double value ); Converts a floating point value to a string with the same content as what std::sprintf(buf, "%f", value) would produce for sufficiently large buf.
You can read on cppreference
f F Precision specifies the exact number of digits to appear after the decimal point character. The default precision is 6
That means that std::to_string rounds after 6 digits.
So I am doing a C++ question about sine.
It says that sin x can be approximated via the polynomial x-(x^3/6)+(x^5/120)-(x^7/5040), and it tells me to output both the approximated sin value and the sin value calculated via cmath.
The input is in degrees, and we have to first convert it to radians then find out sin.
Sample run (only 45 is the input, other our output):
Angle: 45
approxSin = 0.70710647
cmath sin = 0.70710678
I have attempted to write a code for this. When I pressed command+R, nothing happens despite the program saying "build successful". I am new to Xcode, so I am not sure whether I used Xcode incorrectly or I wrote the program incorrectly. Can anyone help?
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(angleDeg-(angleDeg*angleDeg*angleDeg)/6+(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/120-(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/5040);
}
int main(){
float angleDeg;
cin >> angleDeg;
if (angleDeg>180) {
while (angleDeg>180) {
angleDeg = angleDeg-360;
}
} else if (angleDeg<-180) {
while (angleDeg<-180) {
angleDeg = angleDeg+360;
}
}
cout << "approxSin = " << &approxSin << endl;
cout << "cmath sin = " << setprecision(8) << sin(angleDeg);
return 0;
}
my code
My guess about your problem: You run the program, and it patiently waits for your input.
With
cin >> angleDeg;
your program seemingly halts, while it's waiting for you to give some input in the IDE console window. Since you haven't written any prompt there's no output to tell you it's waiting for input.
I suggest you add some output first to ask for the input:
cout << "Please enter angle in degrees: ";
cin >> angleDeg;
When I pressed command+R, nothing happens despite the program saying "build successful".
I guess that the answer by Some programmer dude should solve this issue, but, as noted in the comments, there are much worse problems in the posted code, probably depending by a misunderstanding of how functions should be declared and called in C++.
Consider this:
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(/* Some unreadable expression */);
}
It's enough to generate a couple of warning:
prog.cc:7:22: warning: result of comparison of constant 180 with expression of type 'bool'
is always true [-Wtautological-constant-out-of-range-compare]
if (-180<angleDeg<180) return approxSin(angleDeg-(...));
~~~~~~~~~~~~~^~~~
prog.cc:6:35: warning: all paths through this function will call itself [-Winfinite-recursion]
double approxSin(double angleDeg) {
^
The relational operators are evaluated left-to-right, so that an expressions like -180<angleDeg<180 is read by the compiler as (-180 < angleDeg) < 180. The result of -180 < angleDeg is a bool which leads to the kind warning by the compiler about that expression beeing always true.
It could be written as -180 < angle && angle < 180, but given the OP's assignment, the angle should be tested against plus or minus pi. Also, the alternative branch should be written as well.
The second warning is about the recursive call of the function, which makes no sense, without any alternative path. I can only guess that the OP has misinterpreted how values are returned from a function.
The polynomial itself could be evaluated in a more readable way using std::pow or applying Horner's method. I'll show an example later.
The other big problem (specular, someway) is in the "call" site, which isn't a call at all:
cout << "approxSin = " << &approxSin << endl;
It ends up printing 1 and the reasons can be found in this Q&A: How to print function pointers with cout?
Last, I'd note that while the assignment specifically requires to convert the inputted angle from degrees to radians (as the argument of std::sin is), the posted code only checks the range in degrees, without any conversion.
The following implementation compares different methods for evaluating the sin() function
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
namespace my {
// M_PI while widespread, isn't part of the ISO standard
#ifndef M_PI
constexpr double pi = 3.141592653589793115997963468544185161590576171875;
#else
constexpr double pi = M_PI;
#endif
constexpr double radians_from_degrees(double degrees)
{
return degrees * pi / 180.0;
}
constexpr double convert_angle_to_plus_minus_pi(double angle)
{
while ( angle < -pi )
angle += 2.0 * pi;
while ( angle > pi ) {
angle -= 2.0 * pi;
}
return angle;
}
// Approximates sin(angle), with angle between [-pi, pi], using a polynomial
// Evaluate the polynomial using Horner's method
constexpr double sin_a(double angle)
{
// A radian is passed, but the approximation is good only in [-pi, pi]
angle = convert_angle_to_plus_minus_pi(angle);
// Evaluates p(a) = a - a^3 / 6 + a^5 / 120 - a^7 / 5040
double sq_angle = angle * angle;
return angle * ( 1.0 + sq_angle * (-1.0/6.0 + sq_angle * ( 1.0/120.0 - sq_angle / 5040.0)));
}
double sin_b(double angle) {
angle = convert_angle_to_plus_minus_pi(angle);
return angle - pow(angle, 3) / 6.0 + pow(angle, 5) / 120.0 - pow(angle, 7) / 5040.0;
}
} // End of namespace 'my'
int main()
{
std::cout << " angle std::sin my::sin_a my::sin_b\n"
<< "-----------------------------------------------\n"
<< std::setprecision(8) << std::fixed;
for (int i = -90; i < 475; i += 15)
{
double angle = my::radians_from_degrees(i);
std::cout << std::setw(5) << i
<< std::setw(14) << std::sin(angle)
<< std::setw(14) << my::sin_a(angle)
<< std::setw(14) << my::sin_b(angle) << '\n';
}
return 0;
}
I was doing Exercise of Chapter 3 (Functions) from a Book Called C++ Modules for Gaming.
It is this one question I am not able to Do is to find atanf(4/2) of (2,4) which according to the book and my calculator should give back '63.42' degrees.
Instead it gives me 1.107 degrees.
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
void tani(float a,float b) //Finds the Tan inverse
{
float res;
res = atanf(b / a);
cout << res << endl;
}
int main()
{
cout << "Enter The Points X and Y: " << endl;
float x, y;
cin >> x >> y; //Input
tani(x,y); //calling Function
}
atanf, and the other trigonometric functions in c++ return results in radians. 1.107 radians are 63.426428 degress, so your code is correct.
You can convert radians to degrees by multiplying by 180 and dividing by Pi (the M_PI constant provided by <cmath>):
cout << res * 180.0 / M_PI << endl;
It is giving you correct answer in radians.Simply Convert it to Degree!
void tani(float a, float b) //Finds the Tan inverse
{
float res;
res = atanf(b/ a);
cout << res *(180 / 3.14) << endl;
}
Im trying to convert radians to degrees, but im not getting the same results as google
calculator and the Pi i defined dosent output all number.
If you type in google search: (1 * 180) / 3.14159265 then you get 57.2957796, but my program is
outputting: 57.2958 and if you type in google search Pi you get: 3.14159265, but mine
dosent output the rest, it output: 3.14159
My code is:
#include <iostream>
#define SHOW(X) cout << # X " = " << (X) << endl
using namespace std;
double Pi_test = 3.14159265;
float radian_to_degree(double ENTER) {
double Pi = 3.14159265;
float degrees = (ENTER * 180) / Pi;
return degrees;
}
int main (int argc, char * const argv[]) {
SHOW( radian_to_degree(1) ); // 57.2958 not 57.2957795 like google, why?
SHOW( Pi_test ); // output 3.14159' not 3.14159265, why?
return 0;
}
Please help me fix this, what wrong? any example?
You need to change the default precision:
cout.precision(15);
cout << d << endl;
As stated here, it may be that cout in C++ is rounding your number before displaying it. Try this:
#define SHOW(X) cout << setprecision(some_number) << # X " = " << (X) << endl
Change radian_to_degree to operate on double not float, since double has more precision.
Output the result using std::setprecision
#include <iomanip>
std::cout << std::setprecision(9) << result << "\n";
Even after you change cout's precision, note that double only contains so much data; if you expect your program to spit out 1000 decimal places, a double is not going to give you that much. You'd have to create a data type of your own.
Also, don't define macro functions unless you have to.
I'm writing a program that is using the functions sin() and cos() from the math.h library. However, I noticed I was getting funky results. After searching around and checking my math multiple times, I decided to do a simple check with this:
int main()
{
cout << "sin(45.0) = " << sin(45) << endl;
cout << "cos(45.0) = " << cos(45) << endl;
return 0;
}
And I get this output:
sin(45) = 0.850904
cos(45) = 0.525322
These should be equal right? Is there something special about the math.h library? Am I doing something wrong?
Here are the equations in WolframAlpha:
sin(45)
cos(45)
You should use cmath in C++, rather than the old C header.
std::sin() and std::cos() both take a floating point value representing an angle in radian.
The GCC version of this file includes a handy constant for π, (which does not exist in the C++ standard but) which will make it easier for you to convert degrees to radian:
#include <cmath>
#include <iostream>
double degrees_to_radian(double deg)
{
return deg * M_PI / 180.0;
}
int main()
{
std::cout << "sin(45.0) = " << std::sin(degrees_to_radian(45)) << std::endl;
std::cout << "cos(45.0) = " << std::cos(degrees_to_radian(45)) << std::endl;
}
See it run!
sin and cos expect input in radians not degrees.
try this:
sin(degrees * pi / 180)
Trigonometric functions use radians, not degrees.
sin() and cos() treat your parameter as Radians not Degrees.
Its strange because I cannot get 0 when using cos(1.5707963267948966) which is the radian value for 90 degrees.
long double degrees = 90.0;
long double radians = glm::radians(degrees);
long double result = cos(radians);
The result is equal to 6.1232339957367660e-017 - not kidding.
glm is calculating radians correctly as well, checked it against google.
I used long doubles to make sure it wasn't somehow rounding problems but its not. Just thought this info might help somehow