- ... , , , , , (, , ). (, ?) - " ", BigDecimal - , ( a malloc/free). () ( ), ; , ( ) , .
- , printf . ; , , " " . , , , divide-and-sprintf ( ). - , " " ( , , / ...).
EDIT , ( , ). : .
, !
#include <stdio.h>
#include <time.h>
void doRound(char *s, int n) {
int ii;
int N = n;
if(s[n] - '0' < 5) {
s[N] = '\0';
return;
}
while (n-- > 0) {
if(s[n] == '.') {
n--;
}
if(s[n] - '0' < 9) {
s[n]++;
s[N] = '\0';
return;
}
s[n] = '0';
}
if (n == -1) {
for (ii = N-1; ii >=0; ii--) {
s[ii+1] = s[ii];
}
s[0] = '1';
}
else s[N] = '\0';
}
void longDivision(unsigned int a, unsigned int b, char* r, int n) {
char temp[20];
char c = '0';
int ci = 0;
int t = n + 1;
int dMult = 0;
int di = 0;
while( a > b) {
dMult++;
b *=10;
}
while (10 * a < b) {
dMult --;
a*=10;
}
while( b > a ) {
c++;
b -= a;
}
t--;
temp[ci++] = c;
c = '0';
while( b > 0 && t > 0) {
b *= 10;
t--;
while( b > a ) {
c++;
b -= a;
}
temp[ ci++ ] = c;
c = '0';
}
temp[ ci ] = '\0';
if (dMult > 0) {
r[ di++ ] = '0';
r[ di++ ] = '.';
while( --dMult > 0 ) {
r[ di++ ] = '0';
}
ci = 0;
while( temp[ ci ] != '\0' ) {
r[ di++ ] = temp[ ci++ ];
}
}
else {
ci = 0;
while( temp[ ci ] != '\0') {
r[ di++ ] = temp[ ci++ ];
if( dMult++ == 0 ) r[ di++ ] = '.';
}
}
r[ di ] = '\0';
doRound(r, n+1);
}
int main(void) {
int a, b;
time_t startT, endT;
char result[20];
int ii;
a = 123; b = 700;
longDivision(a, b, result, 5);
printf("the result of %d / %d is %s\n", b, a, result);
printf("the actual result with floating point is %.5f\n", (float) b / (float) a );
a = 7; b = 7000;
longDivision(a, b, result, 5);
printf("the result of %d / %d is %s\n", b, a, result);
a = 3000; b = 29999999;
longDivision(a, b, result, 5);
printf("the result of %d / %d is %s\n", b, a, result);
startT = clock();
for(ii = 1; ii < 100000; ii++) longDivision(a, ii, result, 5);
endT = clock();
printf("time taken: %.2f ms\n", (endT - startT) * 1000.0 / CLOCKS_PER_SEC);
startT = clock();
for(ii = 1; ii < 100000; ii++) sprintf(result, "%.4f", (float) ii / (float) a);
endT = clock();
printf("with floating point, time taken: %.2f ms\n", (endT - startT) * 1000.0 / CLOCKS_PER_SEC);
return 0;
}
( ):
the result of 700 / 123 is 5.6911
the actual result with floating point is 5.69106
the result of 7000 / 7 is 1000.00
the result of 29999999 / 3000 is 10000.0
time taken: 16.95 ms
with floating point, time taken: 35.97 ms