2020年1月11日 星期六

進位轉換

題目:
輸入五個浮點數
輸出

  • 由小到大排序的結果(禁止使用內建的函數)
  • 將排序結果依序轉為下列格式輸出:
  •  二進位
     八進位(最前面加0,ex:19(10) -> 023(8))
     十六進位(最前面加0x,ex:22(10) -> 0x16(16))
     右移一位
     左移一位

範例輸出:







解題思路:
排序用泡沫排序法,可參考這裡
二進位、八進位與十六進位概念相同,而後兩者在printf時有更簡單的方法:
printf("%o",n); //8進位格式輸出
printf("%x",n); //16進位格式輸出
左移與右移的實作則可直接由 >> 或 << 實現,概念可參考此篇

程式碼:
#include <stdio.h>

int main()
{
 float n[5];
 int bi[10], oct[10], hex[10], length = 0;
 printf("Input 5 number: ");
 for (int i = 0; i < 5; i++)
  scanf_s("%f", &n[i]);
 printf("Sorted result: ");
 for (int i = 0; i < 4; i++)
 {
  for (int j = i + 1; j < 5; j++)
  {
   if (n[i] > n[j])
   {
    float temp;
    temp = n[i];
    n[i] = n[j];
    n[j] = temp;
   }
  }
 }
 for (int i = 0; i < 5; i++)
  printf("%.2f ", n[i]);
 int temp = n[0];
 printf("\nConvert %d to binary: ", temp);
 while (1)
 {
  if (temp == 1 || temp == 0)
  {
   bi[length] = temp;
   break;
  }
  bi[length] = temp % 2;
  temp /= 2;
  length++;
 }
 for (int i = length; i >= 0; i--)
  printf("%d", bi[i]);
 temp = n[1];
 length = 0;
 printf("\nConvert %d to octal: ", temp);
 while (1)
 {
  if (temp < 8)
  {
   oct[length] = temp;
   break;
  }
  oct[length] = temp % 8;
  temp /= 8;
  length++;
 }
 for (int i = 2; i >= 0; i--)
 {
  if (i > length)
   printf("0");
  else
   printf("%d", oct[i]);
 }
 temp = n[2];
 length = 0;
 printf("\nConvert %d to hexadecimal: 0x", temp);
 while (1)
 {
  if (temp < 16)
  {
   hex[length] = temp;
   break;
  }
  hex[length] = temp % 16;
  temp /= 16;
  length++;
 }
 for (int i = length; i >= 0; i--)
  printf("%d", hex[i]);
 temp = n[3];
 printf("\n%d right shift 1 bit: ", temp);
 temp = temp >> 1;
 printf("%d", temp);
 temp = n[4];
 printf("\n%d left shift 1 bit: ", temp);
 temp = temp << 1;
 printf("%d", temp);
 return 0;


}

沒有留言:

張貼留言