[ create a new paste ] login | about

Link: http://codepad.org/kyzFoEmb    [ raw code | output | fork ]

C, pasted on Oct 25:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max(a,b) a>b?a:b

long            func(double, double);
int             func2(char *);

long
func(double a, double b)
{
				/* 返り値:変動幅 */
  char            sa[20], sb[20];
  int             i;

  sprintf(sa, "%f", a);
  sprintf(sb, "%f", b);
  i = max(func2(sa), func2(sb));
  while (i--) {
    a *= 10;
    b *= 10;
  }

  return b - a;
}

int
func2(char *s)
{
				/* 返り値:小数点以下の有効桁数 */
  int             i, l;

  i = l = strlen(s);
  while (i--) {
    if (s[i] != '0' || s[i] == '.')
      break;
  }
  l = i;
  while (1) {
    if (s[i] == '.')
      break;
    i--;
  }

  return l - i;
}

int
main()
{
  double          a, b, w[][2] = {{1.2345, 1.2350}, {100.0005, 100.0050}, {80.25, 81.25}, {80.0, 100.0}};
  int             i, debug = 1;

  if (debug) {
    for (i = 0; i < sizeof(w) / sizeof(w[0]); i++) {
      printf("%ld\n", func(w[i][0], w[i][1]));
    }
  } else {
    printf("a b = ");
    scanf("%lf %lf", &a, &b);
    printf("%ld\n", func(a, b));
  }


  return 0;
}


Output:
1
2
3
4
5
45
100
20


Create a new paste based on this one


Comments: