【问题标题】:how to define uint variable as -1 in c#如何在c#中将uint变量定义为-1
【发布时间】:2021-01-24 21:27:40
【问题描述】:

我有以下用 c 编写的函数并且工作正常;但我需要将其转换为 c#。 有一个名为 unsigned int found_at = -1 的变量; c# 中的等价物应该是 uint found_at = -1; 但是我收到编译器错误。你能指导我解决这个问题吗

unsigned int find_adjacent_values(double val, unsigned int start_here, unsigned int end_here, double *vector) {
unsigned int i = start_here, found = 0, found_at = -1;
while (i < end_here-1 && found == 0) {
    if (val >= vector[i] && val < vector[i+1]) { // check whether we found adjacent values
        found = 1;
        found_at = i;
    } else {
        i += 1;
    }
}
return found_at;

}

【问题讨论】:

  • 为什么不直接使用int?这将涵盖所有可能的索引值和 -1。
  • -1 分配给无符号值在两种语言中都是不好的做法。目的是在 C 中编写 UINT_MAX,或在 C# 中编写 uint.MaxValue

标签: c#


【解决方案1】:

试试:

uint found_at = unchecked((uint)-1);

请注意,由于二进制补码的工作方式,该行相当于写作:

uint found_at = uint.MaxValue;

为什么需要unchecked(...) 的解释是here

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2010-12-24
    相关资源
    最近更新 更多