【问题标题】:C program fails to execute more than one statement at the same timeC程序无法同时执行多条语句
【发布时间】:2021-12-07 21:55:59
【问题描述】:

我正在尝试制作一个将用户输入的十进制数转换为二进制和八进制数的 c 程序。

鉴于用户输入 24,我的输出应如下所示:
\n24 十进制是 11000 二进制。
\n十进制的 24 是八进制的 30。\n

但是终端只执行十进制到二进制的转换。 因此,我当前的输出如下所示: \n24 十进制是 11000 二进制。
\n十进制的 0 是八进制的 0。\n

这是有问题的代码。就上下文而言,这两个转换是由两个不同的人编写的:

#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);

        }

八进制转换仅在我删除十进制到二进制部分时执行。但我希望它们同时执行。

【问题讨论】:

  • for(i=0; input&gt;0;i++) 当循环完成时,input 的值为 0。所以当然它不再有用户为下一个循环输入的值。您应该能够通过基本调试自己找到此类问题 - 在调试器中运行您的程序并在运行时对其进行检查。

标签: c printf user-input nested-loops multiple-instances


【解决方案1】:

您的第一个 for 循环操作输入变量,因此在二进制转换后其值始终为 0。将您的代码更改为类似这样,使用附加变量进行计算:

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);

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多