Home > OS >  Print an exponential
Print an exponential

Time:02-10

I'm creating a program that compares numbers with their respective exponents, and indicates which of the three is the smallest. The problem is that I wouldn't want it to perform the operation, for example:

Let's say the smallest number was $4^{8}$, so it would calculate that value, but I want it to just print "4^8" on the screen, or related things, but without doing that operation (in this case, it prints 65536).

int main()
{
    int a, b, c, smaller, x, y, z, for_a, for_b, for_c;

    printf("first value: ");
    scanf("%d", &a);
    printf("Second value: ");
    scanf("%d", &b);
    printf("Third value: ");
    scanf("%d", &c);

    printf("Value of x: ");
    scanf("%d", &x);
    printf("Value of y: ");
    scanf("%d", &y);
    printf("Value of z: ");
    scanf("%d", &z);

    for_a= pow(a, x);
    for_b= pow(b, y);
    for_c= pow(c, z);

    if (for_a< for_b && for_a < for_c){
        smaller= for_a;
    }
    else if (for_b < for_c){
        smaller = for_b;
    }
    else {
        smaller = for_c;
    }

    printf("Smaller= %d\n", smaller);

    return 0;
}

CodePudding user response:

You need to identify the set of data that corresponds to your result. Storing the result only is not enough.

You could do this as follows:

#include <stdio.h>

#typedef struct values_s{
  int base;
  int exponent;
  int result;
} values_t;

#define NUMBER_OF_VALUES 3

int main(void)
{
    values_t values[NUMBER_OF_VALUES];

    for (int i = 0; i < NUMBER_OF_VALUES; i  )
    {
        printf("Base value #%d: ", i 1);
        fflush(stdout);
        int result = scanf("%d", &values[i].base);
        // TODO: Error handling in case result != 1
    }

    for (int i = 0; i < NUMBER_OF_VALUES; i  )
    {
        printf("Exponent #%d: ", i 1);
        fflush(stdout);
        int result = scanf("%d", &values[i].exponent);
        // TODO: Error handling in case result != 1
    }


    for (int i = 0; i < NUMBER_OF_VALUES; i  )
    {
        values[i].result = pow(values[i].base, values[i].exponent);
    }

    int smallest = 0;
    for (int i = 1; i < NUMBER_OF_VALUES; i  )
    {
        if (values[i].result < values[smallest].result)
        {
            smallest = i;
        }
    }

    printf("Smallest: %d^%d = %d\n", values[smallest].base, values[smallest].exponent, values[smallest].result);

    return 0;
}

This is based on the assumptions that your variables of type int are large enough to hold the values you are dealing with. Otherwise you need to adjust accordingly.

  •  Tags:  
  • c
  • Related