在do-while循环中使用unsigned int

MaM28

我是使用c进行编码的新手,而且我一直在尝试将自己的头包裹在无符号整数周围。这是我的代码:

    #include <stdio.h>

     int main(void)
     {
        unsigned int hours;

        do
        {
          printf("Number of hours you spend sleeping a day: ");
          scanf(" %u", &hours);
        }
        while(hours < 0);

        printf("\nYour number is %u", hours);
     }

但是,当我运行代码并使用(-1)时,它不会再次询问该问题,而是将其打印出来(您的电话号码是4294967295)。如果我将unsigned int更改为普通int,则代码可以正常工作。有什么方法可以更改代码以使unsigned int工作?

感谢任何帮助!

chux-恢复莫妮卡

有什么方法可以更改代码以使unsigned int工作?

可能有各种方法。

阅读为int,然后转换为unsigned


给定“您一天睡觉的小时数:”表示一个小的合法范围,大约为0到24,读取为int并转换。

int input;
do {
  puts("Number of hours you spend sleeping a day:");
  if (scanf("%d", &input) != 1) {
    Handle_non_text_input(); // TBD code for non-numeric input like "abc"
  } 
} while (input < 0 || input > 24);
unsigned hours = input;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章