Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to calculate the volume of a cube in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
    Calculate the volume of a cube in idiomatic C.
    ----------------------------------------------
    A cube has equal side lengths. If each side has length "side",
    the volume is:

        volume = side * side * side

    C does not have an exponent operator, and calling pow() for
    integer exponents is slower and unnecessary. Multiplication
    is the fastest and most idiomatic approach.
*/

/* 
    Compute the volume of a cube.
    - side: length of one side (must be non-negative)
    Returns: the cube's volume.
*/
double cube_volume(double side) {
    if (side < 0.0) {
        fprintf(stderr, "Error: side length must be non-negative.\n");
        exit(EXIT_FAILURE);
    }

    // Fastest and idiomatic way to compute side³ in C
    return side * side * side;
}

int main(void) {
    double side = 8.0;

    printf("Side length: %.2f\n", side);
    printf("Volume of cube: %.2f\n", cube_volume(side));

    return 0;
}


/*
run:

Side length: 8.00
Volume of cube: 512.00

*/

 



answered Jul 14, 2021 by avibootz
edited 4 days ago by avibootz
...