Scientic Notation Program

Joined
Nov 9, 2024
Messages
3
Reaction score
0
C++:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    char input[100];
    char *p, numberPart[100];
    double number;
    int exponent;

    if (fgets(input, sizeof(input), stdin) != NULL) {
        // Find the position of 'e' or 'E' in the input string
        p = strchr(input, 'e');
        if (p == NULL) {
            p = strchr(input, 'E');
        }

        if (p != NULL) {
            // Split the string into the number part and the exponent part
            *p = '\0'; // Null-terminate the number part
            strncpy(numberPart, input, sizeof(numberPart));
            numberPart[p - input] = '\0'; // Ensure null termination

            // Convert the number part to a double
            number = strtod(numberPart, NULL);

            // Convert the exponent part to an integer
            exponent = atoi(p + 1);

            // Calculate the final number by multiplying with 10 raised to the power of the exponent
            number = number * pow(10, exponent);
        } else {
            // If there's no 'e' or 'E', just convert the input to a double
            number = strtod(input, NULL);
        }

        // Print the number with 8 decimal places
        printf("%.8f\n", number);
    } else {
        printf("Error.\n");
    }

    return 0;
}

Hi I'm trying to write a code that takes something like 1.2345 E 3 and outputs 1234.50000000. The result should keep 8 digits after the decimal point. use zero(es) if it's fewer than 8 digits; cut it if it's more than 8 digits without rounding. I'm trying to input 2.23456789123456789123456789 e 20 and get an output of 223456789123456789123.45678900 but I can't seem to get it working.
 
Joined
Sep 21, 2022
Messages
177
Reaction score
24
You have 2 choices. Floating point or strings.

Use atof instead of atoi. But floating point can only handle a limited number of significant figures. On the plus side, your program will be 2 lines long.

If you want to have unlimited significant figures, you need to keep everything in strings. The logic for moving the point is tricky, and the program will be long.

I'm not against using strings to store numbers, I do it myself.
 
Joined
Nov 9, 2024
Messages
3
Reaction score
0
It's still not working

C++:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    char input[100];
    char *p, numberPart[100], exponentPart[100];
    char number[100]; // Initialize number as a string
    double exponent; // Change exponent to double

    if (fgets(input, sizeof(input), stdin) != NULL) {
        // Find the position of 'e' or 'E' in the input string
        p = strchr(input, 'e');
        if (p == NULL) {
            p = strchr(input, 'E');
        }

        if (p != NULL) {
            // Split the string into the number part and the exponent part
            *p = '\0'; // Null-terminate the number part
            strncpy(numberPart, input, sizeof(numberPart));
            numberPart[p - input] = '\0'; // Ensure null termination

            // Copy the number part to the number string
            strcpy(number, numberPart);

            // Copy the exponent part to the exponent string
            strcpy(exponentPart, p + 1);

            // Convert the exponent part to a double
            exponent = atof(exponentPart);

            // Calculate the final number by multiplying with 10 raised to the power of the exponent
            double finalNumber = strtod(number, NULL) * pow(10, exponent);

            // Print the final number with 8 decimal places
            printf("%.8f\n", finalNumber);
        } else {
            // If there's no 'e' or 'E', just copy the input to the number string
            strcpy(number, input);

            // Convert the number string to a double and print it with 8 decimal places
            double num = strtod(number, NULL);
            printf("%.8f\n", num);
        }
    } else {
        printf("Error.\n");
    }

    return 0;
}
 
Joined
Nov 9, 2024
Messages
3
Reaction score
0
I have edited the code to solve that previous issue. But now I have another issue, which is to input 1 E 0. It should 1.00000000.

C++:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_MSG_LENGTH 1000

// Function to trim a substring from 'str' starting at index 'beg' and ending at 'end',
// and store the result in 'output'.
void trim(int beg, int end, char* str, char* output) {
    memset(output, '\0', MAX_MSG_LENGTH); // Clear the 'output' buffer.
    for (size_t i = beg; i <= end; i++) {
        output[i - beg] = str[i]; // Copy characters from 'str' to 'out'.
    }
}

void handleNegativeExponent(char* num, int size, int count, int* precision_count, int& i) {
    // Print the initial "0." and the required number of zeros.
    printf("0.");
    for (int j = 0; j < count; j++) {
        printf("0"); // Print each zero for the large exponent.
        (*precision_count)--; // Decrement the precision counter for each zero printed.
    }

    // Adjust the index in the num array to start printing from the first non-zero digit.
    while (num[i] == '0' && i < size - 1) {
        i++;
    }

    // Print the significant digits until the desired precision is reached.
    while (*precision_count > 0 && i < size) {
        char c = num[i++];
        if (c != '.') {
            printf("%c", c);
        }
        (*precision_count)--;
    }

    // Print any remaining zeros to reach the desired precision.
    while (*precision_count > 0) {
        printf("0");
        (*precision_count)--;
    }
}

void handlePositiveExponent(char* num, int size, int count, int* precision_count, int& i) {
    bool is_on_comma = false; // Flag to indicate if we are on the decimal point.
    bool is_on_new_comma = false; // Flag to indicate if we are on the new decimal point after the exponent shift.
    bool print_dot = false; // Flag to indicate if we should print the decimal point.

    // Print the number part with the correct number of decimal places.
    while (*precision_count > 0) {
        if (count == 0) {
            is_on_new_comma = true;
            print_dot = true; // Print the decimal point when the exponent count reaches 0.
        }

        if (print_dot) {
            printf(".");
            print_dot = false;
        }

        if (is_on_comma) {
            count--; // Decrement the exponent count if we are on the comma.
        }

        if (is_on_new_comma) {
            (*precision_count)--; // Decrement the precision counter for the new comma.
        }

        if (i < size) {
            char c = num[i++];
            if (c == '.') {
                is_on_comma = true; // Set the flag if we encounter a decimal point.
            } else {
                printf("%c", c); // Print the character if it's not a decimal point.
            }
        } else {
            printf("0"); // Print zero if we've reached the end of the number part.
        }
    }
}

int main() {
    char input[MAX_MSG_LENGTH];
    fgets(input, MAX_MSG_LENGTH, stdin);
    char num[MAX_MSG_LENGTH];
    char exponent[MAX_MSG_LENGTH];
    bool to_num = true;
    int counter = 0;
    memset(num, '\0', MAX_MSG_LENGTH);
    memset(exponent, '\0', MAX_MSG_LENGTH);
    bool has_comma = false;

    // Parse the input string and separate the number part and the exponent part.
    for (size_t i = 0; input[i] != '\0'; i++) {
        char c = input[i];
        if (c == ' ') {
            continue; // Skip spaces.
        }
        if (c == '.') {
            has_comma = true; // Set the flag if a decimal point is found.
        }
        if (c == 'E' || c == 'e') {
            to_num = false; // Switch to parsing the exponent part.
            counter = 0; // Reset the counter for the exponent part.
            continue;
        }
        if (to_num) {
            num[counter++] = c; // Append character to the number part.
        } else {
            exponent[counter++] = c; // Append character to the exponent part.
        }
    }

    // If there's no decimal point in the number part, add ".0" to it.
    if (!has_comma) {
        sprintf(num, "%s.0", num);
    }

    int size = strlen(num); // Get the length of the number part.
    int precision_count = 8; // Set the precision to 8 decimal places.
    int i = 0; // Reset the index for printing.

    // Handle the case where the exponent is 0.
    if (strcmp(exponent, "0") == 0) {
        bool is_on_comma = false; // Flag to indicate if we are on the decimal point.
        while (precision_count > 0) {
            if (size > i) {
                char c = num[i++];
                if (is_on_comma) {
                    precision_count--;
                }
                if (c == '.') {
                    is_on_comma = true;
                }
                printf("%c", c);
            } else {
                printf("0");
                precision_count--;
            }
        }
    }

    // Handle the case where the exponent is negative.
   if (exponent[0] == '-') {
    // Extract the absolute value of the exponent without the negative sign.
    char newexponent[MAX_MSG_LENGTH];
    int exponent_length = strlen(exponent);
    trim(1, exponent_length - 1, exponent, newexponent);

    // Convert the exponent to an integer.
    int count = atoi(newexponent);

    // Adjust the precision counter to account for the initial "0." that will be printed.
    precision_count = 9; // We add 1 because we've already printed a zero.

    // Ensure the precision counter does not exceed the maximum allowed precision.
    if (count > 8) count = 8;

    // Call the function to handle the large exponent case.
    handleNegativeExponent(num, size, count, &precision_count, i);
} else {
        int count = atoi(exponent); // Convert the exponent to an integer.
        handlePositiveExponent(num, size, count, &precision_count, i);
    }
    printf("\n");
    return 0;
}
 
Joined
Sep 21, 2022
Messages
177
Reaction score
24
The logic for when the exponent equals "0" looks bug free.

If the program is not working, perhaps exponent is a 0 and a newline character.

fgets might be causing the problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top