C++中数的概念,算术运算(加、减、乘、除、求余)
在C++中,数是指数字类型的变量。常见的数字类型包括整型、浮点型和双精度浮点型。其中,整型包括int、long和short,浮点型包括float和double,双精度浮点型包括long double。这些类型在内存中占用的字节数不同,其范围和精度也不同。
算术运算是指对数字进行的基本数学运算。在C++中,常见的算术运算包括加、减、乘、除和求余。下面分别介绍这些运算符及其用法,并用数据模拟展示。
加法运算:用加号(+)表示,表示将两个数相加,返回其和。例如:
int a = 5; int b = 7; int c = a + b; // c的值为12
减法运算:用减号(-)表示,表示将第二个数从第一个数中减去,返回差值。例如:
int a = 7; int b = 5; int c = a - b; // c的值为2
乘法运算:用星号(*)表示,表示将两个数相乘,返回积。例如:
int a = 3; int b = 4; int c = a * b; // c的值为12
除法运算:用除号(/)表示,表示将第一个数除以第二个数,返回商。例如:
int a = 10; int b = 3; int c = a / b; // c的值为3
需要注意的是,当被除数不能整除除数时,C++会将商向下取整。例如:
int a = 10; int b = 4; int c = a / b; // c的值为2
求余运算:用百分号(%)表示,表示求出第一个数除以第二个数的余数。例如:
int a = 10; int b = 3; int c = a % b; // c的值为1
下面通过数据模拟展示这些运算符的使用:
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 3;
int c = a + b; // c的值为8
int d = a - b; // d的值为2
int e = a * b; // e的值为15
int f = a / b; // f的值为1
int g = a % b; // g的值为2
cout << "a + b = " << c << endl;
cout << "a - b = " << d << endl;
cout << "a * b = " << e << endl;
cout << "a / b = " << f << endl;
cout << "a % b = " << g << endl;
return 0;
}除了基本的算术运算,C++中还提供了一些其他的数学函数和运算符,用于更复杂的数学计算。
例如,C++中提供了数学函数库<cmath>,其中包含了各种数学函数,如三角函数、指数函数、对数函数、幂函数等。下面列举几个常用的数学函数:
sqrt函数:求平方根,例如:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double x = 16.0;
double y = sqrt(x); // y的值为4.0
cout << "sqrt(" << x << ") = " << y << endl;
return 0;
}pow函数:求幂,例如:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double x = 2.0;
double y = pow(x, 3); // y的值为8.0
cout << x << "^3 = " << y << endl;
return 0;
}sin函数和cos函数:求正弦和余弦,例如:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double x = 0.0;
double y = sin(x); // y的值为0.0
double z = cos(x); // z的值为1.0
cout << "sin(" << x << ") = " << y << endl;
cout << "cos(" << x << ") = " << z << endl;
return 0;
}此外,C++中还提供了一些特殊的运算符,如自增运算符(++)、自减运算符(--)、取反运算符(-)和取反运算符(!)等。
自增运算符和自减运算符分别表示将变量的值加1和减1,并返回新值。例如:
int a = 5; a++; // a的值变为6 a--; // a的值变为5
取反运算符(-)表示将变量的值取反,例如:
int a = 5; int b = -a; // b的值为-5
取反运算符(!)表示将变量的值取反,并将其转换为布尔类型。如果原始值为0,则返回true,否则返回false。例如:
int a = 0; bool b = !a; // b的值为true int c = 5; bool d = !c; // d的值为false
下面通过数据模拟展示这些数学函数和运算符的使用:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double x = 16.0;
double y = sqrt(x); // y的值为4.0
cout << "sqrt(" << x << ") = " << y << endl;
double a = 2.0;
double b = pow(a, 3); // b的值为8.0
cout << a << "^3 = " << b << endl;
double c = 0.
double d = sin(c); // d的值为0.0
double e = cos(c); // e的值为1.0
cout << "sin(" << c << ") = " << d << endl;
cout << "cos(" << c << ") = " << e << endl;
int f = 5;
f++; // f的值变为6
f--; // f的值变为5
cout << "f++ = " << f++ << endl; // 输出5
cout << "++f = " << ++f << endl; // 输出7
int g = 5;
int h = -g; // h的值为-5
cout << "h = " << h << endl;
int i = 0;
bool j = !i; // j的值为true
int k = 5;
bool l = !k; // l的值为false
cout << "!i = " << j << endl;
cout << "!k = " << l << endl;
return 0;
}
- 上一篇:简单区间类型动态规划
- 下一篇:数的进制:二进制、八进制、十六进制和十进制及其转换
