As you know from your basic algebra, variables can be assigned any name. However, in C++, the computer cannot solve equations. Variables can only be assigned values.
There are mainly 2 types of variables in C++: Strings and numbers. Classification is as follows:
String type:
Char (character)
string (an array of char)
Number type:
int
unsigned long (big int)
float (floating-point, i.e. decimal)
double (super precise floating-point number)
bool (Boolean, i.e. true and false)
To define a variable, we type in the code:
[var_type] [var_name];
And can be assigned values on instantiation:
[var_type] [var_name] = [var_value];
So for example, I can assign an int to hold value 3:
int abc = 3;
or Boolean xyz with false:
bool xyz = false;
You can assign multiple values:
int a = 3, b, c = 5;
to create a string hihi with value hello me:
string hihi = “hello me”;
Arithmetic:
C++ can do simple +, -, /, *, % (modulo)
A definition is as follows:
int a = 0; //create a; assign a = 0
a + 1; //add 1 to a
a – 1; //minus
a /1; //divide
a*1; //multiply
a%1; //modulo
a++; //a + 1 and store new value in a
a--; //a – 1 and store new value in a
a += 2; // add value 2 to a and store
a -= 2; // subtract 2 from a and store
a /= 2; //divide 2 from a and store
a *= 2; //multiply 2 to a and store
That done, let us analyse a simple problem.
Evaluate the value of (9– 2) / ( (180.5 + 2) / 3):
A simple c++ program:
#include <iostream>
using namespace std;
int main() {
int a,b,c;
a = 9 - 2;
b = 180.5 + 2;
c = b / 3;
cout << a / c << endl;
return 0;
}
Of course, I can put the whole expression (9– 2) / ( (180.5 + 2) / 3) into C++, but this is to illustrate the picture better.
Hope you get a better picture of how to handle vars in C++, ciao!
No comments:
Post a Comment