C/Data Type/Long

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

Choosing the correct type: long

/* Choosing the correct type: short */
#include <stdio.h>
void main()
{
  const float per = 4.5f;
  short a = 23500;            
  short b = 19300;                       
  short c = 21600;                       
  float revenue = 0.0f;                  
  long total = a+b+c; /* Calculate quarterly total */
  /* Output monthly sales and total for the quarter */
  printf("\n a: %d\n b: %d\n c: %d",a,b,c);
  
  printf("\n Total: %ld",total);
  /* Calculate the total revenue and output it */
  revenue = total/150*per;
  printf("\nSales revenue  is:$%.2f\n",revenue);
}


Convert long to short int

  
#include <stdio.h>
int main(void)
{
  short int si;
  long int li;
  li = 100000;
  si = li; /* convert long to short int */
  printf("%hd", si);
  return 0;
}


long value array

#include <stdio.h>
void main()
{
   long longArray[] = {1L, 2L, 3L};
   printf(" first element address: %p value: %d\n", 
                                               longArray, *longArray);
   printf("second element address: %p value: %d\n", longArray + 1,
                                                   *(longArray + 1));
   printf(" third element address: %p value: %d\n",longArray + 2,
                                                   *(longArray + 2));
   printf("    type long occupies: %d bytes\n", sizeof(long));
}


Read long from keyboard

#include <stdio.h>
void main()
{
  long feet = 0L;               /* A whole number of feet                    */
 
   printf("Enter long: ");
   scanf("%ld", &feet);
   printf("your input is %ld", feet);
}


Summing integers - compact version

#include <stdio.h>
void main()
{
   long sum = 0L; 
   int count = 10; /* The number of integers to be summed */
   int i = 0;     /* The loop counter                    */
   /* Sum integers from 1 to count */
   for (i = 1 ; i<= count ; sum += i++ );
   printf("\nTotal of the first %d numbers is %ld\n", count, sum);
}


Use nested if to analyze numbers

/* Use nested if to analyze numbers */
#include <stdio.h>
#include <limits.h>            /* For LONG_MAX */
void main()
{
  long test = 112L;              /* Stores the integer to be checked */
  printf("Enter an integer less than %ld:", LONG_MAX);        
  scanf(" %ld", &test);                                       
   if( test % 2L == 0L) {
     printf("The number %ld is even", test);
     if ( (test/2L) % 2L == 0L) {
       printf("\nHalf of %ld is also even", test);
       printf("\nThat"s interesting isn"t it?\n");
     }
   }
   else
     printf("The number %ld is odd\n", test);
}