C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Click here to view code image


printf("In 3 years, I'll be %d years old.\n", age + 3);

If you want to multiply and divide, you can do so by using the * and / symbols. The following
statement assigns a value to a variable using multiplication and division:


Click here to view code image


newFactor = fact * 1.2 / 0.5;

Warning

If you put integers on both sides of the division symbol (/), C computes the integer
division result. Study the following program to get familiar with integer division and
regular division. The comments explain the results calculated from the divisions, but
you can always double-check by compiling the program and running it yourself.

Click here to view code image


// Example program #1 from Chapter 9 of
// Absolute Beginner's Guide to C, 3rd Edition
// File Chapter9ex1.c
/* This is a sample program that demonstrates math operators, and
the different types of division. */
#include <stdio.h>

main()
{
// Two sets of equivalent variables, with one set
// floating-point and the other integer
float a = 19.0;
float b = 5.0;
float floatAnswer;
int x = 19;
int y = 5;
int intAnswer;
// Using two float variables creates an answer of 3.8
floatAnswer = a / b;
printf("%.1f divided by %.1f equals %.1f\n", a, b, floatAnswer);
floatAnswer = x /y; //Take 2 creates an answer of 3.0
printf("%d divided by %d equals %.1f\n", x, y, floatAnswer);
// This will also be 3, as it truncates and doesn't round up
intAnswer = a / b;
printf("%.1f divided by %.1f equals %d\n", a, b, intAnswer);
Free download pdf