首页 > ACM题库 > HDU-杭电 > hdu 2424 Gary’s Calculator-高精度-[解题报告]C++
2014
01-26

hdu 2424 Gary’s Calculator-高精度-[解题报告]C++

Gary’s Calculator

问题描述 :

Gary has finally decided to find a calculator to avoid making simple calculational mistakes in his math exam. Unable to find a suitable calculator in the market with enough precision, Gary has designed a high-precision calculator himself. Can you help him to write the necessary program that will make his design possible?
For simplicity, you only need to consider two kinds of calculations in your program: addition and multiplication. It is guaranteed that all input numbers to the calculator are non-negative and without leading zeroes.

输入:

There are multiple test cases in the input file. Each test case starts with one positive integer N (N < 20), followed by a line containing N strings, describing the expression which Gary’s calculator should evaluate. Each of the N strings might be a string representing a non-negative integer, a "*", or a "+". No integer in the input will exceed 109.
Input ends with End-of-File.

输出:

There are multiple test cases in the input file. Each test case starts with one positive integer N (N < 20), followed by a line containing N strings, describing the expression which Gary’s calculator should evaluate. Each of the N strings might be a string representing a non-negative integer, a "*", or a "+". No integer in the input will exceed 109.
Input ends with End-of-File.

样例输入:

3
100 + 600
3
20 * 4
2
+ 500
5
20 + 300 * 20

样例输出:

Case 1: 700
Case 2: 80
Case 3: Invalid Expression!
Case 4: 6020

void mult(char a[],char b[],char s[])
{
    int i,j,k=0,alen,blen,sum=0,res[165][165]={0},flag=0;//通过设置数组可以改变精度这个为165位
    char result[165];
    alen=strlen(a);blen=strlen(b); 
	
    for (i=0;i<alen;i++)
		for (j=0;j<blen;j++) res[i][j]=(a[i]-'0')*(b[j]-'0');
		
		for (i=alen-1;i>=0;i--)
        {
            for (j=blen-1;j>=0;j--) 
				sum=sum+res[i+blen-j-1][j];
            result[k]=sum%10;
            k=k+1;
            sum=sum/10;
        }
		
		for (i=blen-2;i>=0;i--)
        {
            for (j=0;j<=i;j++) sum=sum+res[i-j][j];
            result[k]=sum%10;
            k=k+1;
            sum=sum/10;
        }
		if (sum!=0) {result[k]=sum;k=k+1;}
		
		for (i=0;i<k;i++) result[i]+='0';
		for (i=k-1;i>=0;i--) s[i]=result[k-1-i];
		s[k]='\0';
		
		while(1)
        {
			if (strlen(s)!=strlen(a)&&s[0]=='0') 
				strcpy(s,s+1);
			else
				break;
        }
}

解题转自:http://blog.csdn.net/dst111188/article/details/12318453


  1. bottes vernies blanches

    I appreciate the efforts you men and women place in to share blogs on such sort of matters, it was certainly useful. Keep Posting!