【问题标题】:How to display values of an array in C?如何在C中显示数组的值?
【发布时间】:2017-04-29 15:35:45
【问题描述】:

我用 C 语言编写了以下代码,以使用函数查找数字的二进制。

//C program to find the binary equivalent of a number using functions

#include <stdio.h>
void bineq(int);
void main()
{    
    int a=5,b=3;           //Initialize two numbers        
    printf("The binary equivalent of a= \n");
    bineq(a);
    printf("The binary equivalent of b= \n");
    bineq(b);

}
void bineq(int x)         // Function Definition.
   {
       int p[50];
       int i=0,t,j;
       t=x;

       while(t>=0)
       {
           p[i]=t%2;
           i++;
           if(t==0){
             break;}
           t=t/2;   
       }  

       for(j=i-1;j>=0;j--)
       {
            printf("%d ",p[i]);

       }

   }

当我运行代码时,我得到以下值:

 The binary equivalent of a= -1610823072 -1610823072 -1610823072 -1610823072 

 The binary equivalent of b= 32644 32644 32644                                                       

当我在C Tutor(在线编译器)中运行代码时,bineq函数中的printf语句出现如下错误:

ERROR: Conditional jump or move depends on uninitialized value(s) (Stopped 
running after the first error. Please fix your code.)

5 的二进制正确存储在整数数组 p 中,但我无法向后显示每个整数。

我想以最简单的方式解决问题。我是否遗漏了代码中的任何逻辑或任何一行?

【问题讨论】:

    标签: c arrays integer


    【解决方案1】:

    bineq的for循环中,改变

    printf("%d ",p[i]);
    

    printf("%d ",p[j]); 
    

    你也不需要检查if(t==0) break;你的while会做同样的事情只需将while(t&gt;=0)更改为while(t&gt;0)

    【讨论】:

    • 我给了 t==0 break;这样当我打印二进制数时也会出现零。谢谢你的解决方案。我忽略了这么一个小错误。
    • 实际上,如果我进行按位运算 AND 喜欢: printf("\n按位运算 AND %d & %d: %d",a,b,1100&11001); //12 & 25 我得到输出 72 而不是 8
    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 2016-04-02
    • 2020-06-12
    • 2021-07-19
    • 2014-07-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    相关资源
    最近更新 更多