| long double |
| double |
| float |
| unsigned long long int |
| long long int |
| unsigned long int |
| long int |
| unsigned int |
| int |
years * interestRate
在乘法发生之前,years 中的值将升级为 double 类型。area = length * width;
因为存储在 length 和 width 中的值是相同的数据类型,所以它们都不会被转换为任何其他数据类型。但是,乘法的结果将被升级为 long int 类型,这样才可以存储到 area 中。
int x;
double y = 3.75;
x = y; // x被赋值为3,y仍然保留3.75
int quantity1 = 6;
double quantity2 = 3.7;
double total;
total = quantity1 + quantity2;
static_cast<DataType>(Value)
其中 Value 是要转换的变量或文字值,DataType 是要转换的目标数据类型。以下是使用类型转换表达式的代码示例:
double number = 3.7;
int val;
val = static_cast<int>(number);
类型转换表达式在 C++ 不能自动执行所需转换的情况下很有用。
下面的程序显示了使用类型强制转换表达式来防止发生整除法的示例。
//This program uses a type cast to avoid an integer division.
#include <iostream>
using namespace std;
int main()
{
intbooks, months;
double booksPerMonth;
// Get user inputs
cout << "How many books do you plan to read? ";
cin >> books;
cout << "How many months will it take you to read them? ";
cin >> months;
// Compute and display books read per month
booksPerMonth = static_cast<double>(books) / months;
cout << "That is " << booksPerMonth << " books per month.\n";
return 0;
}
程序输出结果:
How many books do you plan to read? 30
How many months will it take you to read them? 7
That is 4.28571 books per month.
booksPerMonth = static cast<double>(books) / months;
变量 books 是一个整数,但是它的值的副本在除法运算之前被转换为 double 类型。如果没有此类型转换表达式,则将执行整除法,导致错误的答案。值得一提的是,如果按以下语句改写此行,则整除法仍然会发生:booksPerMonth = static_cast <double> (books / months);
因为括号内的操作在其他操作之前完成,所以除法运算符将对其两个整数操作数执行整除法,books / month 表达式的结果将是 4,然后将 4 转换为 double 类型的值 4.0,这就是将赋给 booksPerMonth 的值。
//This program prints a character from its ASCII code.
#include <iostream>
using namespace std;
int main()
{
int number = 65;
//Display the value of the number variable
cout << number << endl;
// Use a type cast to display the value of number
// converted to the char data type
cout << static_cast<char>(number) << endl;
return 0;
}
程序输出结果:
65
A
booksPerMonth = (double)books / months;
预标准 C++ 形式类型强制转换表达式也是将要转换的数据类型放在其值要转换的操作数之前,但它将括号放在操作数周围,而不是围绕数据类型。这种类型转换表示法被称为功能性表示法,示例如下:booksPerMonth = double(books) / months;
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有