C Tutorial/Data Type/int Calculation

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Divide Integer

<source lang="cpp">#include <stdio.h> int main(void) {

 int cookies = 45;                      
 int children = 7;                      
 int cookies_per_child = 0;             
 int cookies_left_over = 0;             
 
 cookies_per_child = cookies/children;  
 printf("You have %d children and %d cookies", children, cookies);
 printf("\nGive each child %d cookies.", cookies_per_child);
 cookies_left_over = cookies%children;
 printf("\nThere are %d cookies left over.\n", cookies_left_over);
 return 0;

}</source>

You have 7 children and 45 cookies
     Give each child 6 cookies.
     There are 3 cookies left over.

If both operands i1 and i2 are integers, the expression i1/i2 provides integer division

<source lang="cpp">#include<stdio.h> main( ) {

 int a = 1,b =2;
 printf("\n a = %f",a/b);
 printf("\n a = %d",a/b);

}</source>

a = 0.000000
 a = 0

Simple calculations

<source lang="cpp">#include <stdio.h> int main(void) {

 int Total_Pets;
 int Cats;
 int Dogs;
 int Ponies;
 int Others;
 Cats = 2;
 Dogs = 1;
 Ponies = 1;
 Others = 46;
 Total_Pets = Cats + Dogs + Ponies + Others;
 printf("We have %d pets in total", Total_Pets);  /* Output the result */
 return 0;

}</source>

We have 50 pets in total

Sum the integers from 1 to a user-specified number

<source lang="cpp">#include <stdio.h> int main(void) {

 long sum = 0L;
 int count = 100;
 for(int i = 1 ; i <= count ; i++){
   sum += i;
 }  
 printf("\nTotal of the first %d numbers is %ld\n", count, sum);
 return 0;

}</source>

Total of the first 100 numbers is 5050