• C程式的練習題 4【千萬火急】!

    Posted on 二月 6th, 2010 王子聃 2 comments

    Write a C program that reads one unsigned integer, reverses
    the integer, and prints the reverse of the integer and the sum of the integer and its reverse.
    For example, the reverse of 1234 is 4321 and the reverse of 120 is 21.

    先說一下,不用C++,要用C函數或陣列或迴圈,然後要有說明喔!

     

    2 responses to “C程式的練習題 4【千萬火急】!” RSS icon

    • #include<stdio.h>

      int main(){

      int in=0, sum=0, i=1, tmp=0;

      printf("Input a number : ");
      scanf("%d",&in);

      printf("Inverse is:");

      while(in/i>0){
       if(i==1)
        tmp=in-(in/(i*10)*10);

       else
        tmp=(in/i)%10;

       sum=sum+tmp;
       printf("%d",tmp);
       i=i*10;
      }
      printf("\n");
      printf("Sum is : %d\n",sum);
      return 0;
      }

    • 底下例子完全採字串處理:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>

      // 製作反向字串
      char *reverse(const char *in)
      {
      char *out;
      int i;

      if(in == NULL)
      return NULL;

      i = strlen(in);
      out = (char *)malloc(i + 1);

      // in 由前往後讀過去, out 由後往前寫回來
      out[i] = 0;
      while(i > 0)
      {
      i–;
      out[i] = *in;
      in++;
      }

      return out;
      }

      // 製作兩字串的數字和 (假設內容均為 ‘0′ - ‘9′)
      char *add(const char *a, const char *b)
      {
      char *out;
      int i, j, max;
      int carry;

      if((a == NULL) || (b == NULL))
      return NULL;

      // 判斷最後輸出字串長度, 包含進位
      i = strlen(a);
      j = strlen(b);
      if(i > j)
      max = i + 1;
      else
      max = j + 1;
      out = (char *)malloc(max + 1);
      out[max] = 0;
      out[0] = ‘ ‘;

      // out 由後往前寫回來
      carry = 0;
      while(max > 0)
      {
      char c = 0;
      // 加上 a 的目前位數
      if(i > 0)
      {
      i–;
      c += a[i] - ‘0′;
      }
      // 加上 b 的目前位數
      if(j > 0)
      {
      j–;
      c += b[j] - ‘0′;
      }

      // 加上上一位數的進位
      c += carry;
      carry = 0;
      // 檢查是否需要進位
      if(c > 9)
      {
      carry = 1;
      c -= 10;
      }

      // 寫入輸出字串
      max–;
      if((c > 0) || (max > 0))
      out[max] = ‘0′ + c;
      }

      return out;
      }

      int main()
      {
      const char *str = "123456789";
      char *rev;
      char *sum;

      rev = reverse(str);
      printf("%s %s\n", str, rev);
      sum = add(str, rev);
      printf("sum = %s\n", sum);
      return 0;
      }

      執行結果:

      123456789 987654321
      sum = 1111111110


    Leave a reply

    抱歉,您必須要登入才能發表迴響喔!