【问题标题】:Variable declaration in C with random value随机值的 C 变量声明
【发布时间】:2021-09-29 10:09:49
【问题描述】:

我刚刚尝试为abd 提供相同的值,并且每次运行我的代码时都会生成一个随机值。

#include <stdio.h>

int main()
{
    int a = 4; //type declaration instructions
    int b = 999, c, d;
    a = b = d;

    printf("The value of a and b  is %d and %d \n", a, b);
    return 999;
}

【问题讨论】:

标签: c var variable-declaration


【解决方案1】:

让我们逐行进行。

  1. 声明一个整数a,并将其初始化为值4

    int a = 4;
    
  2. 声明 3 个整数 bcd,并将 b 初始化为 999。由于cd 没有初始化,它们有垃圾值(之前存储在内存块中的值,现在已分配给cd)。

    int b = 999,c,d;
    
  3. 错误代码。 d中的垃圾值设置为ab

    a=b=d;
    

更正 - 要么初始化 d,要么不将 ab 设置为 d

#include <stdio.h>

int main()
{
    int a = 4; //type decleration instructions
    int b = 999,c,d = 1000; // initialise d
    a=b=d;
    printf("The value of a and b  is %d and %d \n",a,b);
    return 999;
}

【讨论】:

  • (random values from anywhere in the memory) 它不是来自内存中的任何地方。
【解决方案2】:
You declared variable c and d without assigning its values so random values are assigned to d .
hence assignment operator works right to left so 
    a=b=d
first:
   b=d works so random value of d goes in b 
and then : 
   a=b works so that random value goes in a
so try using=>
d=b=a
  you will get:
a=4
b=4
d=4

【讨论】:

  • 欢迎来到 StackOverflow!请拨打tour 了解本网站的运作方式。如您所见,缩进文本会将其格式化为源代码。我敢肯定这不是你想要的。请edit你的答案。
【解决方案3】:

您在每次执行该程序时获得随机值背后的原因是,如果未定义变量,C 会分配垃圾值(即任何随机数)。

但是这个程序完全依赖于编译器,因为如果我们不定义它,很少有编译器默认将值分配为 0。

因此,此程序的输出可能会因您使用的 C 编译器而异。例如,如果您正在使用一些在线 C 编译器,那么它很可能会给出 0 作为输出,而有些可能会给出随机值(垃圾值)作为输出。

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 2021-12-25
    • 1970-01-01
    • 2012-04-01
    • 2022-06-17
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多