#ifndef LENGTH_H_
#define LENGTH_H_
#include <stdio.h>
#include <stdlib.h>
#define True 1
#define False 0
typedef enum {
Mile = 0,
Yard,
Feet,
Inch,
MaxType
}unit_e;
extern unsigned int dimension[MaxType];
typedef struct {
unsigned int value;
unit_e unit;
unsigned int absolute;
}length_t;
int Length(unsigned int value, unit_e unit, length_t* const length);
int LengthEqual(const length_t* const len1, const length_t* const len2);
int LengthAdd(const length_t* const len1, const length_t* const len2, length_t* const ret);
#endif
#include "Length.h"
unsigned int dimension[MaxType] = {1760*3*12, 3*12, 12, 1};
int Length(unsigned int value, unit_e unit, length_t* const length) {
if (value < 0 || unit >= MaxType || NULL == length) {
return -1;
}
length->value = value;
length->unit = unit;
length->absolute = value * dimension[length->unit];
return 0;
}
int LengthEqual(const length_t* const len1, const length_t* const len2) {
return (len1->absolute == len2->absolute ? True : False);
}
int LengthAdd(const length_t* const len1, const length_t* const len2, length_t* const ret) {
if (len1 == NULL || len2 == NULL || ret == NULL)
return -1;
ret->absolute = len1->absolute + len2->absolute;
ret->value = ret->absolute;
ret->unit = Inch;
return 0;
}
#include <assert.h>
#include "Length.h"
void main(void) {
length_t *len1 = (length_t *)malloc(sizeof(length_t));
length_t *len2 = (length_t *)malloc(sizeof(length_t));
length_t *ret = (length_t *)malloc(sizeof(length_t));
if (NULL == len1 || NULL == len2 || NULL == ret) {
goto malloc_error;
}
Length(13, Inch, len1);
Length(11, Inch, len2);
Length(0, Inch, ret);
LengthAdd(len1, len2, ret);
Length(2, Feet, len1);
assert(LengthEqual(ret, len1));
Length(3, Feet, len1);
Length(2, Yard, len2);
LengthAdd(len1, len2, ret);
Length(3, Yard, len1);
assert(LengthEqual(ret, len1));
printf("Value Compare Test : All PASS!\n");
free(len1);
free(len2);
free(ret);
exit(0);
malloc_error:
printf("Malloc Error! Test Falid!\n");
exit(-1);
}