mirror of
https://gitee.com/Lamdonn/varch.git
synced 2025-12-06 16:56:42 +08:00
110 lines
2.3 KiB
C
110 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <float.h>
|
|
#include <math.h>
|
|
#include <math.h>
|
|
#include <ctype.h>
|
|
#if defined(TEST_TARGET_calculate)
|
|
#include <varch/command.h>
|
|
#include <varch/calculate.h>
|
|
#else
|
|
#include "init.h"
|
|
#include "command.h"
|
|
#include "calculate.h"
|
|
#endif
|
|
|
|
static int command_calculate(int argc, char *argv[])
|
|
{
|
|
double r = NAN;
|
|
if (argc < 2) return 0;
|
|
r = calculate(argv[1]);
|
|
if (fabs(floor(r) - r) <= DBL_EPSILON && fabs(r) < 1.0e60) printf("%.0lf\r\n", r);
|
|
else if (fabs(r) < 1.0e-6 || fabs(r) > 1.0e9) printf("%e\r\n", r);
|
|
else
|
|
{
|
|
char p[64];
|
|
int len = 0;
|
|
len = sprintf(p, "%lf", r);
|
|
while (len > 0 && p[len-1] == '0' && p[len-2] != '.') {p[--len] = 0;}
|
|
printf("%s\r\n", p);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
static double factorial(double n)
|
|
{
|
|
if (n < 1) return 1;
|
|
return n * factorial(n - 1);
|
|
}
|
|
|
|
static double K()
|
|
{
|
|
return 1024.0;
|
|
}
|
|
|
|
static void usage(void)
|
|
{
|
|
printf(
|
|
"Usage: calculate [opt] [arg]\n"
|
|
"\n"
|
|
"options:\n"
|
|
" -h Print help\n"
|
|
" -v Print version\n"
|
|
"\n"
|
|
"argument:\n"
|
|
" <read> Test default read function\n"
|
|
" <write> Test default write function\n"
|
|
);
|
|
}
|
|
|
|
static int test(int argc, char *argv[])
|
|
{
|
|
/* reset getopt */
|
|
command_opt_init();
|
|
|
|
while (1)
|
|
{
|
|
int opt = command_getopt(argc, argv, "hv");
|
|
if (opt == -1) break;
|
|
|
|
switch (opt)
|
|
{
|
|
case 'v' :
|
|
printf("calculate version %d.%d.%d\r\n", CALCULATE_V_MAJOR, CALCULATE_V_MINOR, CALCULATE_V_PATCH);
|
|
return 0;
|
|
case '?':
|
|
printf("Unknown option `%c`\r\n", command_optopt);
|
|
return -1;
|
|
case 'h' :
|
|
default:
|
|
usage();
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
printf("mul %lf\r\n", calculate(" ( 99 * 3 ) "));
|
|
printf("min %lf\r\n", calculate(" min (12, 3)"));
|
|
printf("sin %lf\r\n", calculate("sin ( 11 / 2 * pi ) + 100 "));
|
|
|
|
calculate_export("fac", factorial, 1);
|
|
calculate_export("K", K, 0);
|
|
|
|
command_export("cal", command_calculate);
|
|
|
|
return 0;
|
|
}
|
|
|
|
#if defined(TEST_TARGET_calculate)
|
|
int main(int argc, char *argv[])
|
|
{
|
|
return test(argc, argv);
|
|
}
|
|
#else
|
|
void test_calculate(void)
|
|
{
|
|
command_export("calculate", test);
|
|
}
|
|
init_export_app(test_calculate);
|
|
#endif
|