網頁

2008年3月21日 星期五

【教學】C語言,作業六 - 計算超大數相乘。(2008.03.22原始檔OK)

本作業基本要求如下:
1. 每次讀取兩個值,進行相乘運算後,印出乘積。
2. 當輸入的兩個值都是 0 時,則程式停止。
3. 必須使用陣列。
3. 必須製作函數,以呼叫進行運算。
※第一個整數的範圍在0~ 10^32(10的32次方),第二個整數的範圍是0~99。

1.先將大數的最小位數與小數相乘。
2.將相乘的值與欲印出的變數 相加及完成程式(注意:檢查是否需要進位。)
3.建議用整數陣列來接收答案,最後用迴圈讓他印出整串數字。

(2008.03.09)


這個東西讓我忙了整天(=_=)...希望這個對大家有幫助,至於原始碼我過幾天會Po上來的


#include stdio.h
#include stdlib.h
#include string.h
void calc(char input[],int output[]);//計算答案用的函數 

int n=1;//num=欲相乘之數、n=陣列使用之變數

short int num;
int main(void)
{
    char input[88];//input=輸入字串
    int output['n']={0},i;//output=n個整數陣列(記錄答案)i=迴圈用變數 
    bool judge;//判斷答案是否為0之布林變數 
printf("第一個數請在87位數以內。第二個數請在0~32767以內。\n");
    while(1)
    {
        printf("請輸入欲相乘兩數:");
        scanf("%s %d",input,&num);
        if((int)input[0]==48 && num==0)//若輸入兩個0則停止程式 
            break;
        calc(input,output);//呼叫calc函數 
        for(i=n-1;i>=0;i--){
            if(output[i]>0){//如果答案不為0,輸出答案 
                judge=1;
                for(i=i;i>=0;i--)
                {
                    printf("%d",output[i]);
                    output[i]=0;
                }
                break;
            }
        }
        if(judge==0)//judge=0(如果答案為0) 
           printf("0");
        judge=0;//調整judge布林值 
        printf("\n");
    }
    system("pause");
    return 0;
}
void calc(char input[],int output[])
{//i=變數、j=output陣列用之變數
    int i,j=0,k=0,in_length=0,num_length=0,temp;
//in_length=輸入字串之長度、out_length=輸入整數之長度、temp=暫存答案用         in_length=strlen(input);//查出輸入的字串共多少字元
    temp=num;//查出輸入的整數共多少字元
    for(i=1;i<88;i++)
    {
        temp/=10;
        if(temp==0){
            num_length=i;
            break;
        }
    }
    n=in_length+num_length;//設定output的陣列長度
    for(i=in_length-1;i>=0;i--)//字串最後位與整數相乘 
    {//i=用在字元陣列之變數 
        temp=((int)input[i]-48)*num;//temp接收數字的乘積 
        while(j<=n-1)//將乘積給output陣列接收 
        {
            for(k=j;temp>0;k++)
            {//temp接收乘積最小位數 
                output[k]+=temp%10;
                if(output[k]>=10){//超過10進位 
                    output[k]%=10;
                    output[k+1]+=1;
                }
                temp/=10;
            }
            j++;
            break;
        }
    }
}
//////////////////////////////////////////END//////////////////////////////////////////

執行結果:



※有哪裡不懂得可以MSN問我,如果有錯誤的地方,可以直接在底下回覆糾正我的錯誤。

2 則留言:

  1. ㄎㄎ  我學的是C++ 但都差不多
    我即將邁向專業的程式設計大師
    哈哈哈

    回覆刪除
  2. 呵呵~~~原來是大師呀XD

    那以後你設計個簡單、又讓我玩都玩不膩的遊戲給我好了XD

    回覆刪除