我是 C++ 编程的初学者......我正在练习,我遇到了这个问题......在这里我试图在复合运算符上使用 static_cast......我实际上是在尝试将两个整数相除并得到答案作为双...这是代码:
#include <iostream>
using namespace std;
int main() {
int g {0}, h {0};
cout << "Enter g and h: " << endl;
cin >> g >> h;
static_cast<double>(g) /= (h);
cout << "g: " << g << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在我知道我可以将 int 改为 double ......或者做这样的事情:
i = g/h;
cout << static_cast<double>(i) << endl;
Run Code Online (Sandbox Code Playgroud)
但让我们挑战一下……如果我们真的需要输入整数(而不是双精度数)怎么办?
这是我得到的错误:
error: lvalue required as left operand of assignment
Run Code Online (Sandbox Code Playgroud)
示例:通过强制转换更改数据类型
#include <iostream>
using namespace std;
int main()
{
int total {0};
int num1 {0}, num2 {0}, num3{0};
const int count {3};
cout << "Enter 3 integers: ";
cin >> num1 >> num2 >> num3;
total = num1 + num2 + num3;
double average {0.0};
//This is where it confuses almost everyone. Imagine total is equal to 50, so average is equal to 16.66.
//But the problem is that total is an integer so you will only get 16 as answer.
//The solution is to convert it by casting.
average = static_cast<double>(total) / count;
//average = (double)total/count; //Old-Style code
cout << "The 3 numbers are: " << num1 << ", " << num2 << ", " << num3 << endl;
cout << "The sum of the numbers are: " << total << endl;
cout << "The average of the numbers is: " << average << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为您误解了static_cast.
static_cast将(如果可能)将值转换为另一种类型,并为您提供新类型1的结果右值。一个右值是不是可以分配给2(不像左值,这是你在你的错误消息,看到的)。
在 C++ 中,变量的类型在声明期间只给出一次。对于该变量的整个生命周期,它将是它声明的类型(请注意,这与较弱的类型语言(如 Python 或 JavaScript)不同)。
在回复您的示例时,请注意没有变量正在更改其类型。
average = static_cast<double>(total) / count;
Run Code Online (Sandbox Code Playgroud)
average被声明为 a double,它仍然是 a double。这里的神奇之处在于您正在投射total到double. 所以static_cast<double>(total)给你一个double与整数等效的值total(但这不再是total!它现在是一个临时的 unnamed double)。然后将未命名的double除以count,并将结果分配给average。
1. 要转换的类型是引用类型的情况除外。(感谢布赖恩!)
2. 对于本机类型。“除非您明确禁止,否则可以将任何类类型右值分配给它。” (谢谢内森!)