Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- #define MAX_LINE_LENGTH 100
- enum positionState {
- POSITION_STATE_WHOLE,
- POSITION_STATE_DECIMAL,
- POSITION_STATE_NOTATION
- };
- int mygetline(char line[], int max) {
- int c, i;
- for (i = 0; i < max && (c = getchar()) != EOF && c != '\n'; i++) {
- line[i] = c;
- }
- return i;
- }
- int isDigit(char input) {
- return (input >= '0' && input <= '9') ? 1 : 0;
- }
- long power(int base, int exponent) {
- long result = (exponent > 0) ? base : 0;
- for (int i = 0; i < exponent - 1; i++) {
- result *= base;
- }
- return result;
- }
- float atof(char input[]) {
- int sign = 1;
- int whole = 0;
- float decimal = 0;
- int decimalCount = 0;
- int notationExponents = 0;
- int notationSign = 1;
- int i = 0;
- while ((input[i] < '0' || input[i] > '9') && input[i] != '+' && input[i] != '-') {
- i++;
- }
- if (input[i] == '+' || input[i] == '-') {
- sign = (input[i++] == '-') ? -1 : sign;
- }
- enum positionState position = POSITION_STATE_WHOLE;
- while (input[i] != '\n' && input[i] != ' ' && input[i] != '\t' && input[i] != '\0') {
- // Return -1 for invalid characters.
- if ((input[i] < '0' || input[i] > '9') && input[i] != 'e' && input[i] != 'E' && input[i] != '-' && input[i] != '+' && input[i] != '.') {
- return -1;
- }
- // Handle whole numbers
- if (position == POSITION_STATE_WHOLE) {
- if (isDigit(input[i])) {
- whole = whole * 10 + (input[i] - '0');
- }
- }
- // Handle decimals
- if (position == POSITION_STATE_DECIMAL) {
- if (isDigit(input[i])) {
- decimalCount++;
- decimal = decimal * 10 + (input[i] - '0');
- }
- }
- position = (input[i] == '.') ? POSITION_STATE_DECIMAL : position;
- // Handle notation
- if (position == POSITION_STATE_NOTATION) {
- if (input[i] == '-') {
- notationSign = -1;
- i++;
- }
- if (isDigit(input[i])) {
- notationExponents = notationExponents * 10 + (input[i] - '0');
- }
- }
- position = (input[i] == 'e' || input[i] == 'E') ? POSITION_STATE_NOTATION : position;
- // Next char in input
- i++;
- }
- // Calculate result
- double result = whole;
- if (decimalCount > 0) {
- result += decimal / power(10, decimalCount);
- }
- if (notationExponents > 0) {
- if (notationSign > 0) {
- result *= power(10, notationExponents);
- } else {
- result /= power(10, notationExponents);
- }
- }
- return sign * result;
- };
- int main() {
- int c;
- char line[MAX_LINE_LENGTH];
- while (mygetline(line, MAX_LINE_LENGTH)) {
- printf("%f", atof(line));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement