StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #4 (U1): Type Conversion — Integer Division vs Casting
Download
  1. C Programming
  2. C Programming Practice
Program #3 (U1): Simple Interest (SI) & Compound Interest (CI) : Program #5 (U1): Temperature Converter (°C ↔ °F)
C Programming Practice

Task: Read two integers a and b. Show the result of a/b (integer division) versus (float)a/b (floating-point division). Also show a few safe variants and explain why the outputs differ because of type casting and usual arithmetic conversions.

 
/* 

  Program: Type Conversion — Integer Division vs Explicit Cast (U1)

  What it does:

    - Reads two integers a and b.

    - Prints: (1) a/b as integer division, (2) (float)a/b, (3) a/(float)b, (4) (double)a/b.

    - Explains that when both operands are integers, C performs integer division (truncation toward zero).

    - Any cast to float/double promotes the operation to floating-point division (keeps the fractional part).

  Note: Guard against division by zero.

*/

 
#include <stdio.h>

 
int main(void) {

    int a, b;

    int intDiv;

    float fDiv1, fDiv2;

    double dDiv;

 
    printf("Enter two integers (a b): ");

    if (scanf("%d %d", &a, &b) != 2) {

        printf("Invalid input. Please enter exactly two integers.\n");

        return 0;

    }

 
    if (b == 0) {

        printf("Error: division by zero is undefined.\n");

        return 0;

    }

 
    /* (1) Integer division: fractional part is discarded (truncation toward zero). */

    intDiv = a / b;

 
    /* (2) & (3) Casting either operand to float promotes the operation to float division. */

    fDiv1 = (float)a / b;     /* Cast numerator */

    fDiv2 = a / (float)b;     /* Cast denominator */

 
    /* (4) Casting to double gives a double-precision result. */

    dDiv  = (double)a / b;

 
    printf("Integer division (a/b)      = %d\n", intDiv);

    printf("Float division ((float)a/b) = %.6f\n", fDiv1);

    printf("Float division (a/(float)b) = %.6f\n", fDiv2);

    printf("Double division ((double)a/b) = %.10f\n", dDiv);

 
    /* Tip:

       Another common idiom is multiplying by 1.0 to force floating-point: 1.0 * a / b

       Example check:

         For a=7, b=2 -> intDiv = 3, float/double divisions = 3.5

    */

 
    return 0;

}

 

 

Program #3 (U1): Simple Interest (SI) & Compound Interest (CI) Program #5 (U1): Temperature Converter (°C ↔ °F)
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website