Untitled
Basic Math Operations Using C++
Introduction to Basic Mathematical Operations in C++
- C++ is capable of performing basic mathematical operations.
- Example program demonstrating these mathematical operations:
#include<iostream>
using namespace std;
int main() {
int number1;
int number2;
int result;
cout<<"Please enter number1 & number2";
cin>>number1>>number2;
result = number1 + number2;
result = number1 - number2;
result = number1 * number2;
result = number1 / number2;
result = number1 % number2;
cout<<result;
return 0;
}
Explanation of Program Components
- Operands: The variables
number1andnumber2are operands in the expressions. - Operators: Various operators are used, including addition (
+), subtraction (-), multiplication (*), division (/), and modulus (%). - Modulus Operator: The modulus operator is only applicable for integer data types.
- Division Behavior: The division of integers yields an integer result, truncating any decimals. This necessitates understanding order of precedence among the arithmetic operators.
Example of Operator Precedence and Outcomes
- Two illustrative cases of operator precedence in C++:
Case I
y = 5 / 2 * 5 + 3 * 5 + 7;
cout<<y;
- Expected Output: y = 32
Case II
y = 5 * 5 / 2 + 3 * 5 + 7;
cout<<y;
- Expected Output: y = 34
Precedence of Arithmetic Operators
- Order of Operations:
- ( ) Parentheses: Evaluated first. Inner expressions take precedence when nested.
- *, /, %: Multiplication, division, and modulus are evaluated second from left to right.
- +, -: Addition and subtraction are evaluated last, also from left to right.
Example Code Demonstrating Averaging
- Initial implementation of average calculation (Incorrect due to precedence):
#include<iostream>
using namespace std;
int main() {
int number1 = 74, number2 = 82, number3 = 88;
double average;
average = number1 + number2 + number3 / 3; // Incorrect
cout<<average;
return 0;
}
- Correct approach which uses parentheses to ensure correct order:
#include<iostream>
using namespace std;
int main() {
int number1 = 74, number2 = 82, number3 = 88;
double average;
average = (number1 + number2 + number3) / 3; // Correct
cout<<average;
return 0;
}
Using Constant Variables
- Code example utilizing a constant for grades:
#include<iostream>
using namespace std;
int main() {
int number1 = 74, number2 = 82, number3 = 88;
double average;
const int numGrades = 3;
average = (number1 + number2 + number3) / numGrades;
cout<<average;
return 0;
}
- Any attempt to modify a constant variable results in a compilation error: "Error: assignment of read-only variable."
- Constants are beneficial for repeated usage, such as the mathematical constant pi in calculations.
Advanced Mathematical Functions in C++
- Various mathematical functions are available through the
<cmath>library. To include this library, use:
#include<cmath>
Category of Functions
Trigonometric Functions:
cos(x): Returns cosine of anglexin radians.sin(x): Returns sine of anglexin radians.tan(x): Returns tangent of anglexin radians.acos(x): Computes the principal value of arc cosine; domain error for inputs not in[-1, 1].asin(x): Computes the principal value of arc sine; similar domain restrictions.atan(x): Returns arc tangent in range[−π/2, +π/2].
Exponential and Logarithmic Functions:
exp(x): Returnseraised to powerx.log(x): Natural logarithm ofx; domain error for negative values.log10(x): Common logarithm (base 10) ofx; domain error for negative values.
Power Functions:
pow(base, exponent): Returns base raised to the power of exponent e.g.,pow(7.0, 3.0)gives7^3.sqrt(x): Returns square root; domain error for negative values.cbrt(x): Returns cubic root ofx.
Rounding and Remainder Functions:
ceil(x): Rounds x upward to nearest integral value.floor(x): Rounds x downward to nearest integral value.fmod(numerator, denominator): Returns floating-point remainder of division.trunc(x): Rounds x toward zero.round(x): Rounds to nearest integral value, with halfway cases away from zero.
Absolute Value Functions:
fabs(x): Returns absolute value ofx: |x|.abs(x): Returns absolute value as well.
Example of Using Trigonometric Functions
- Example code to calculate trigonometric ratios:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
const double pi = 3.141592;
double angle = pi/6;
cout<<"******** Calculating Trigonometric Ratios ********"<<endl;
cout<<"All calculations on Angle "+to_string(angle)+" Radians"<<endl;
cout<<"cos("<<angle<<") = "<<cos(angle)<<endl;
cout<<"sin("<<angle<<") = "<<sin(angle)<<endl;
cout<<"tan("<<angle<<") = "<<tan(angle)<<endl;
cout<<"******** Calculations Terminated ********"<<endl;
return 0;
}
- Task: Write a program to take angle input from the user in degrees and find its cosine, sine, and tangent.
Using Exponential and Logarithmic Functions
- Example program using logarithmic functions:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double num = 10.3;
cout<<"exp("<<num<<") = "<<exp(num)<<endl;
cout<<"log("<<num<<") = "<<log(num)<<endl;
cout<<"log10("<<num<<") = "<<log10(num)<<endl;
return 0;
}
Using Power Functions Example
- Example program for power functions:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double num1 = 10.3, num2 = 2.0;
cout<<"pow("<<num1<<","<<num2<<") = "<<pow(num1,num2)<<endl;
cout<<"sqrt("<<num1<<") = "<<sqrt(num1)<<endl;
cout<<"cbrt("<<num1<<") = "<<cbrt(num1)<<endl;
return 0;
}
Using Rounding and Remainder Functions Example
- Example demonstrating rounding functions:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double num1 = 2.3, num2 = 3.8, num3 = 5.5, num4 = -2.3, num5 = -3.8, num6 = -5.5;
cout<<"value\tround\tfloor\tceil\ttrunc\n";
cout<<"-----\t-----\t-----\t----\t-----\n";
cout<<num1<<"\t"<<round(num1)<<"\t"<<floor(num1)<<"\t"<<ceil(num1)<<"\t"<<trunc(num1) <<"\n";
cout<<num2<<"\t"<<round(num2)<<"\t"<<floor(num2)<<"\t"<<ceil(num2)<<"\t"<<trunc(num2) <<"\n";
cout<<num3<<"\t"<<round(num3)<<"\t"<<floor(num3)<<"\t"<<ceil(num3)<<"\t"<<trunc(num3) <<"\n";
cout<<num4<<"\t"<<round(num4)<<"\t"<<floor(num4)<<"\t"<<ceil(num4)<<"\t"<<trunc(num4) <<"\n";
cout<<num5<<"\t"<<round(num5)<<"\t"<<floor(num5)<<"\t"<<ceil(num5)<<"\t"<<trunc(num5) <<"\n";
cout<<num6<<"\t"<<round(num6)<<"\t"<<floor(num6)<<"\t"<<ceil(num6)<<"\t"<<trunc(num6) <<"\n";
return 0;
}
Understanding Floating Points and Type Casting
- Example of type casting in C++:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
float num1 = -9.5;
int num2 = 101;
cout<<(int)num1;
cout<<endl<<(float)num2/10;
return 0;
}
Formatting Output with
- Sample code to demonstrate output control using
<iomanip>:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main() {
double planck = 6.62607004e-34;
double gravitation = 6.67408e-11;
double charge = 1.60217662e-19;
cout<<"********Output Without Precision********"<<endl;
cout<<"Planck's Constant = "+to_string(planck)<<endl;
cout<<"Gravitational Constant = "+to_string(gravitation)<<endl;
cout<<"Charge on electron = "+to_string(charge)<<endl;
cout<<"********Output with Precision of 10********"<<endl;
cout<<setprecision(10);
cout<<"Planck's Constant = "+to_string(planck)<<endl;
cout<<"Gravitational Constant = "+to_string(gravitation)<<endl;
cout<<"Charge on electron = "+to_string(charge)<<endl;
return 0;
}
Exercises and Additional Tasks
- Write a note on the importance of operator precedence and why calculators handle this differently.
- Explore using
<cmath>functions applied to integer types and address possible issues. - Experiment with formatting functions
scientificandfixedin C++ for different outputs. - Implement expressions such as:
- Test erroneous inputs on functions such as: