Jump to content

Simple math in C++

From IdeaWazaWiki

Simple C++ Math

So, first things first. Lets add the math libraries to our C++ project. That way we have the ability to do useful math functions such as powers, square roots and the like.

#include <cmath> // ANSI C++ way. For ANSI C you should do: #include <math.h>

Note that the math library is one of the 18 ANSI C language standard libraries that can be imported in C++. Now you have made many useful functions available to your program. Now, let's do some math.

Adding, Subtracting, Multiplying and Dividing

These are all very straightforward, and do not even need the math library to work. The syntax for basic math with these operands are as follows:

variable = operand operator operand;

So an example of this could be something like

int myResult;
myResult = 5 + 6;  // A value of 11 will be stored into the integer myResult

Now, C++ allows this all to be very flexible. So you can mix numbers, variables, floats, ints and all sorts of things together.

int five=5, six=6, twelve=12;
float pi=3.14, myResult;
myResult = six * pi + twelve; // since pi is float, no need to cast six and twelve to float
myResult = myResult - five;

C++ will perform operations via BEMDAS (or PEMDAS, or however you learned it in middle school). That means brackets (or parantheses) will be computed first. Then exponents, then multiplication and division, and then finally addition and subtraction. The above code will take the number six, and then convert it to a floating point number. Then it will multiply 6 by pi, which will return a floating point number. Then twelve, which has been converted to a float, will be added to the result. So myResult at this point will contain 30.84. Then five will be converted to a float and subtracted from myResult. The result will be 25.84.

This should be pretty straightforward. Now, take a look at the last line of the above code. Notice that we are taking the variable and adding another value to it, and then dumping it back into itself. You've just had to type the same variable name twice in a row, which could lead to typos, and also takes up time. There is an easier way to do this! Each of the following lines has an equivalent line of code that follows.

myResult = myResult+5;
myResult += 5;

myResult = myResult-5;
myResult -= 5;

myResult = myResult*5;
myResult *= 5;

myResult = myResult/5;
myResult /= 5;

See the pattern? We reach another very common situation. There are many instances where you will want to increment a variable by one, or decrement it by one. This is very common in counters and loops. For example, everytime the user hits a button on the keyboard you may want to increment a counter by 1. So, here's an easy way to add one, or subtract one from a variable.

int counter=0;  // Initialize the variable
counter++;      // Adds 1 to the variable counter
counter--;      // Subtracts 1 from the variable counter

Basic Math Library Functions

Now it is time to browse a few of the functions that are available from the math library. We can take the square roots of numbers, we can take powers of numbers, etc. The syntax is as follows:

float myValue=25, myResult;
myResult = sqrt(myValue);       // Squareroot the variable myValue, and store it into variable myResult
myResult = pow(myResult,2.00);  // Square the variable myResult, and then store it back into myResult

Let's investigate what this does. First, this program takes the square root of 25 and stored into myResult. This leaves a 5.00 in myResult. Then this value is squared and stored back into itself. This means 25.00 will be stored in myResult. So, more simply:

pow(myValue,myPower);    // myValue is the base and myPower is the exponent

For a list of functions, see math.h.

End of lesson 3

You should now be able to get C++ to do some simple math for you. In reality, it never gets much more complex than this. Almost everything you will write will be based on just a few simple operators. Thanks for reading this far. Hopefully you have learned something. Still, for your enhancement, following is the program that finds prime numbers until specified number:



#include<iostream>
using namespace std;
int main(){
	int n;
	cin>>n;
	for(int i=2;i<n;++i){
		int count=0;
		for(int j=1;j<=n;++j)
			if(!(i%j))
				++count;
		if(count==2)
			cout<<i<<endl;
	}
	return 0;
}



Where To Go Next

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science