我需要将一个int变量转换为double
我的朋友正在尝试将某种计算作为上课的一项任务,但他遇到了一些麻烦...希望您能为他提供帮助.
My friend is trying to make some kind of calculation as a task for class, and he's having some trouble... I hope you can help him.
问题在于他从用户那里获得了int的输入(必须是,这是任务的一部分).他正在尝试在下面的代码中将其转换为double,但这是行不通的.结果仍然是int.
The problem is that he gets an input from the user as int (it has to be, it's a part of the task). He is trying to convert it to double in the code below, but this doesn't work. The results are int anyway.
double firstSolution = ((b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
double secondSolution = ((b2 * a11 - b1 * a21) / (a11 * a22 - a12 * a21));
如果您需要更多说明,我会请他提供.预先感谢!
If you need more explanation, I'll ask him for it. Thanks in advance!
您必须将除法运算符的一个(或两个)参数强制转换为 double
:
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
由于您两次执行相同的计算,因此我建议重构您的代码:
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
这以相同的方式起作用,但是现在有一个隐式转换为双精度.从 int
到 double
的这种转换是
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.