简体   繁体   English

C程序无法同时执行多条语句

[英]C program fails to execute more than one statement at the same time

I am trying to make ac program that converts the decimal the user entered into a binary and octal number.我正在尝试制作将用户输入的十进制数转换为二进制和八进制数的 ac 程序。

Given the user entered 24, my output should look like this:鉴于用户输入 24,我的输出应如下所示:

24 in Decimal is 11000 in Binary.十进制的 24 是二进制的 11000。
24 in Decimal is 30 in Octal.十进制的 24 是八进制的 30。

But the terminal only executes the decimal to binary conversion.但是终端只执行十进制到二进制的转换。 Hence my current output look like this:因此,我当前的输出如下所示:

24 in Decimal is 11000 in Binary.十进制的 24 是二进制的 11000。
0 in Decimal is 0 in Octal.十进制中的 0 是八进制中的 0。

Here is the code in question.这是有问题的代码。 For context, the two conversions were written by two separate people:就上下文而言,这两个转换是由两个不同的人编写的:

#include <stdlib.h>

int main()
{
            int a[10], input, i;  //variables for binary and the user input
            int oct = 0, rem = 0, place = 1; //variables for octal
            printf("Enter a number in decimal: ");
            scanf("%d", &input);

//decimal to binary conversion            
            printf("\n%d in Decimal is ", input);
            for(i=0; input>0;i++)
                {
                    a[i]=input%2;
                    input=input/2;
                }
            for(i=i-1;i>=0;i--)    
            {printf("%d",a[i]);}

//decimal to octal conversion
            printf("\n%d in Decimal is ", input);
            while (input)
            {rem = input % 8;
            oct = oct + rem * place;
            input = input / 8;
            place = place * 10;}
            printf("%d in Octal.", oct);

        }

The octal conversion only executes when I remove the decimal to binary portion.八进制转换仅在我删除十进制到二进制部分时执行。 But I want both of them to execute at the same time.但我希望它们同时执行。

Your first for loop manipulates the input variable, therefore its value is always 0 after the binary conversion.您的第一个 for 循环操作输入变量,因此其值在二进制转换后始终为 0。 Change your code to something like this, using an additional variable to do the computation on:将您的代码更改为这样的内容,使用附加变量进行计算:

printf("\n%d in Decimal is ", input);
int temp = input;
for(i=0; temp>0;i++)
{
     a[i]=temp%2;
     temp=temp/2;
}
for(i=i-1;i>=0;i--)    
{
    printf("%d",a[i]);
}

//decimal to octal conversion
printf("\n%d in Decimal is ", input);
temp = input;
while (temp)
{
    rem = temp% 8;
    oct = oct + rem * place;
    temp = temp / 8;
    place = place * 10;
}
printf("%d in Octal.", oct);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM