【问题标题】:Why is my if else statement not showing results of one of the conditions?为什么我的 if else 语句没有显示条件之一的结果?
【发布时间】:2017-02-10 02:07:38
【问题描述】:

我一直在让自己发疯,试图弄清楚为什么第一个 if 语句(如果饿了是真还是假)不会显示适当的响应。如果你打对或错,它就不会打印声明。我觉得这是一个愚蠢的明显错误......但我无法发现它。 ----编辑----

第一个条件/if 语句不会显示任何内容(饥饿) 如果你输入 1 或 0,它不会显示 prinft 语句来配合它。

#include<stdio.h>
#include<stdbool.h>

int main (void){

_Bool hungry = 0;
_Bool thirsty = 0;
_Bool sleepy = 0;


printf("Are you hungry? (1 - true 0 - false) : ");
scanf("%d", &hungry);

printf("Are you thirsty?: ");
scanf("%d", &thirsty);

printf("Are you sleepy?: ");
scanf("%d", &sleepy);


if ( hungry ) {
    printf("Ordering manty \n");
}
     if ( thirsty ) {
        printf("Ordering pot of hot tea \n");
    } 
    else {
        printf("Ordering cup of water \n");
    } 
    if  ( sleepy ) {
        printf("Ordering black coffee \n");
    }
    else {
    printf("Ordering baursaki \n");
    }

} 

【问题讨论】:

  • “不会显示适当的响应”。那么它具体是做什么的呢?请描述确切输入、预期输出和实际输出。
  • 它不会对第一个条件(饥饿)显示任何响应
  • 如果您输入 1 或 0,我将除(饥饿的)if 语句之外的所有内容都注释掉,即便如此,在输入 1 为真时它也不会显示 printf 语句。抱歉没有解释。
  • "警告:格式指定类型 'int *' 但参数的类型为 'bool *'" 是编译器应该给你的警告。

标签: c boolean


【解决方案1】:

此代码导致未定义的行为:

_Bool hungry = 0;
scanf("%d", &hungry);

%d 格式说明符需要int * 类型的参数,但您提供了_Bool *。 printf 和 scanf 系列不进行任何类型转换——由程序员确保提供正确的参数类型。

事实上,_Bool 没有格式说明符。您必须读入另一个变量,然后分配给布尔值,例如:

int temp = 0;
scanf("%d", &temp);
hungry = temp;

您可能想检查scanf 的返回值,也可能还要检查temp 并在输入意外时采取措施。

【讨论】:

    【解决方案2】:

    sizeof(_Bool) 是 1,或 1 字节。

    通过尝试将scanf-%d 放入其中,您是在尝试将 4 字节放入仅足够容纳 1 字节的空间中。从那时起,您就有了未定义的行为。

    我会推荐:

    int temp;             // Temp is 4-bytes. (assuming 32-bit system)
    scanf("%d", &temp);   // %d matches 4-byte int.
    hungry = !!temp;      // !! converts int value into _Bool value.
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多