我正在嘗試制作將用戶輸入的十進制數轉換為二進制和八進制數的 ac 程式。
鑒于用戶輸入 24,我的輸出應如下所示:
十進制的 24 是二進制的 11000。
十進制的 24 是八進制的 30。
但是終端只執行十進制到二進制的轉換。因此,我當前的輸出如下所示:
十進制的 24 是二進制的 11000。
十進制中的 0 是八進制中的 0。
這是有問題的代碼。就背景關系而言,這兩個轉換是由兩個不同的人撰寫的:
#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);
}
八進制轉換僅在我洗掉十進制到二進制部分時執行。但我希望它們同時執行。
uj5u.com熱心網友回復:
您的第一個 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331935.html
上一篇:在c中拆分字串和計數標記
