我刚刚创建了一个使用该Floor方法的小程序:
public static void Main(string[] args)
{
int i;
decimal[] t = new decimal[30];
for(i=0; i<t.Length; i++)
{
t[i]=Math.Floor(i/6);
}
for(i=0; i<t.Length; i++)
{
Console.WriteLine(""+t[i]);
}
Console.ReadKey(true);
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.SharpDevelop返回此错误:
以下方法或属性之间的调用不明确:'System.Math.Floor(decimal)'和'System.Math.Floor(double)'(CS0121)
与此行有关:
t[i] = Math.Floor(i/6);
Run Code Online (Sandbox Code Playgroud)
有人能解释我有什么不对吗?
另外:起初我尝试写作,int[] t = new int[30];因为我的程序只返回整数.但是它返回了第二个错误,说我应该使用类型decimal而不是类型int.我也尝试使用类型float和类型,double但它也没有用.似乎只有这种类型decimal有效.我也想知道为什么?
有人能解释我有什么不对吗?
编译器正在告诉你到底出了什么问题 - 调用是不明确的.您尝试使用调用结果分配到decimal数组中的事实与编译器无关 - 它只查看方法的参数以尝试确定要调用的方法.
类型表达的i/6是int,这可以转换为两个double和decimal,既没有转化为比其它"更好",所以该呼叫是不明确的.其实,你并不真的需要调用的话-你与表达反正进行整数运算i / 6这是相当于- ,这截断向零Floor非负数.你只想存储整数...你只需要:
public static void Main(string[] args)
{
// While "values" isn't a particularly descriptive name, it's better
// than "t"
int[] values = new int[30];
// Limit the scope of i - declare it in the loop header
for (int i = 0; i < values.Length; i++)
{
values[i] = i / 6;
}
// You don't need the index here, so use a foreach loop. Generally prefer
// foreach over for
foreach (int value in values)
{
// You don't need any string concatenation here...
Console.WriteLine(value);
}
Console.ReadKey(true);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1499 次 |
| 最近记录: |