gpt4 book ai didi

c# - 除以两位小数并将结果转换为 int

转载 作者:太空狗 更新时间:2023-10-30 00:37:27 26 4
gpt4 key购买 nike

我正在尝试将除法结果转换为 C# 中的 int

这是我的代码:

decimal testDecimal = 5.00; // testDecimal always is dividable by 0.25 with 0 rest
int times=0;

int times = testDecimal / Convert.ToDecimal(0.250);

// error returned -> Cannot implicitly convert type 'decimal' to 'int'.

如果我将类型转换更改为

int times = (int) testDecimal / Convert.ToDecimal(0.250); 
//also returns an error: Cannot implicitly convert type 'decimal' to 'int'

我怎样才能得到整数形式的结果 (20)?我究竟做错了什么?

最佳答案

试试这个:

 times = (int)(testDecimal / Convert.ToDecimal(0.250));

如果没有额外的括号,它会尝试仅将 testDecimal 转换为整数,然后尝试将 int/decimal 结果隐式转换为整数,这就是导致错误的原因。

在一个不相关的注释中,您试图两次声明变量“times”。

关于c# - 除以两位小数并将结果转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51158069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com