【问题标题】:How to assign true to a boolean variable in c language如何在c语言中将true分配给布尔变量
【发布时间】:2019-07-16 17:23:19
【问题描述】:

如果整数变量year是闰年,我想给布尔变量leapYear赋值(闰年是4的倍数,如果是100的倍数,也必须是400的倍数。 )在一个c程序中

这是我尝试过的代码。

bool leapYear;
int year;

printf("Enter a year ");
scanf("%d", &year);
if (year %4 = 0 || year %100 = 0 || year %400 = 0)
    printf("true");

我试图编译我编写的代码,但它给出了一个错误,提示未知类型名称'bool'。

【问题讨论】:

  • 与问题无关:你所有的= 都应该是==
  • #include <stdbool.h>
  • 另外,你的闰年逻辑是错误的,它对所有 4 的倍数都返回 true,它不能正确地处理世纪异常。见stackoverflow.com/questions/3029417/…
  • 使用_Bool inatead
  • 即使您使用_Bool b = true;,您仍然需要#include <stdbool.h> 才能接受true

标签: c boolean boolean-expression


【解决方案1】:

你必须包含头文件<stdbool.h>

在此文件中bool 被定义为宏并扩展为C 标准无符号整数类型_Bool

任何不等于0 的值都将转换为1 并分配给_Bool 类型的变量。

例如,将变量设置为 true 你可以写

bool leapYear = 1;

头文件还包含truefalse 的宏。

这是一个演示程序

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

int main(void) 
{
    bool leapYear = true;

    printf( "leapYear = %u\n", leapYear );

    return 0;
}

它的输出是

leapYear = 1

如果您不想包含标头,则可以只使用标准整数类型_Bool

例如

#include <stdio.h>

int main(void) 
{
    _Bool leapYear = 1;

    printf( "leapYear = %u\n", leapYear );

    return 0;
}

甚至int这样的类型

int leapYear = 1;

在 C 语言中,如果表达式为真,则返回整数 1,否则返回 0。

【讨论】:

    【解决方案2】:

    您需要#include &lt;stdbool.h&gt; 才能使用布尔值,但在 C 语言中我们通常使用整数。它的工作方式是0为假,其他为真。

    在你的情况下,

    int leapYear = 0;    // default to false
    ... 
    leapYear = 1;    // set to true. Any non-zero value works.
    

    【讨论】:

    • bool 自 C99 以来的标准类型
    • @EugeneSh。对不起,错误的术语。我的意思是默认情况下不包含它,您必须自己包含它。
    • _Bool 是一种标准类型,不包含任何标题。所以,是的,布尔值“默认包含”。它们必须如此,因为_Bool 有不适用于任何其他类型的特殊规则。 bool 只是 _Bool 的别名,由 stdbool.h 提供方便。
    • @JohnBollinger 我的理解是使用_Bool 被认为是不好的做法
    • 不知道你是从哪里得到这个想法的,@ZacharyOldham。如果有的话,我倾向于反过来说——在 C 中使用 bool 可能会出现问题,因为它可能会与为该符号提供自己的定义的代码发生冲突,而且这样的代码并不少见。但这完全无关紧要。 _Bools 是布尔值。 stdbool.h 的bool 是同一类型,但您不需要标头具有布尔值。 (而_Bool 一个整数。)
    【解决方案3】:

    正如大家所指出的,您的主要问题是未能#include &lt;stdbool.h&gt;。此外,您在条件中使用= 而不是==。我个人不会尝试使用单个条件,因为闰年​​的规则很复杂,很难转化为单个语句。为了清楚起见,我会使用一个函数:

    #include <stdbool.h>
    
    bool is_leap(int year) {
        if (0 == (year % 400)) return true;
        if (0 == (year % 100) && year > 1582) return false;
        if (0 == (year % 4)) return true;
        return false;
    }
    
    int main(int argc, char *argv[]) {
        . . .
        bool leap = is_leap(2019);
        . . .
    }
    

    【讨论】:

    • 减 1。1700 通常被认为是非闰年 ref。建议0 == (year % 100) &amp;&amp; year &gt;= 17000 == (year % 100) &amp;&amp; year &gt; 1582
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2013-06-24
    • 2010-10-13
    • 2018-03-15
    • 2022-10-05
    相关资源
    最近更新 更多