C - Squaring a integer with value 0 is outputting 1?

122 views Asked by At
decPlace_volume = floor(volume+.05) - ceil(volume); //should output -1, 0, or 1
decPlace_volume = pow(decPlace_volume,2); //should the above == -1, this should turn it into 1 while making 0 remain 0

The only allowed libraries for my assignment are stdio.h and math.h.

My assignment is pretty simple - find the surface area and volume of a cylinder, and the precision of the output should be 1 unless the output decimal would be 0, in which case the decimal shouldn't be printed.

The above is what I came up with (same thing for surface area just different variables). If the output of the first line is -1, the second line should make it positive, and 0 should stay zero (integer so shouldn't need to worry about funky stuff).

For some reason, when the first line outputs a 0, the second line is outputting 1. Is there something I'm missing here?

3

There are 3 answers

0
Weather Vane On

Your question asks to suppress the decimal if it would be 0, here is one way to do that

#include<stdio.h>
#include<string.h>

int main()
{
    char buffer[25];
    double volume;

    volume = 1.234;
    sprintf (buffer, "%.1f", volume);       // convert to string with 1 place
    if (strstr(buffer, ".0") != NULL)       // examine string
        sprintf (buffer, "%.0f", volume);   // redo the string with 0 places
    printf ("Volume = %s\n", buffer);

    volume = 1.01;
    sprintf (buffer, "%.1f", volume);
    if (strstr(buffer, ".0") != NULL)
        sprintf (buffer, "%.0f", volume);
    printf ("Volume = %s\n", buffer);

    return 0;
}

Program output:

Volume = 1.2
Volume = 1
0
chux - Reinstate Monica On

the precision of the output should be 1 unless the output decimal would be 0, in which case the decimal shouldn't be printed.

OP's approach is subject to problems near multiples of 0.01 due to the typical binary implementation of floating point. Instead post-processes the output of the unaltered volume.

Use snprintf()

double volume = foo();
char buffer[100];
buffer[0] = 0;
int len = snprintf(buffer, sizeof buffer, "%.1f", volume);
if (len > 0 && buffer[len-1] == '0') buffer[--len] = '\0';
puts(buffer);
0
bpucka On

Alright fellas thanks for the help, I figured it out. For some reason I thought that my first line could output a 1, but it won't. Instead of

decPlace_volume = pow(decPlace_volume,2);

to convert, I just made a line for decPlace_volume *= -1;.

Thanks again!