【发布时间】:2019-12-04 20:32:49
【问题描述】:
我是 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;
}
现在我知道我可以将 int 更改为 double...或执行以下操作:
i = g/h;
cout << static_cast<double>(i) << endl;
但是让我们来挑战一下……如果我们真的需要输入整数(不是双精度数)怎么办?
这是我得到的错误:
error: lvalue required as left operand of assignment
示例:通过强制转换更改数据类型
#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;
}
【问题讨论】:
-
我不清楚你想在这里做什么。您是否正在尝试将
g从整数变量转换为双精度变量? -
是的..这就是我想要做的
-
这是不可能的。
g被声明为int。它永远是int。 -
变量声明后不能改变类型。
-
我不确定,但我已经看到他们通过强制转换更改数据类型的示例......让我通过编辑将其实际发布到我的问题中