渥瑞達 Linux Unix下C語言軟體開發視頻教程 筆記4

來源:互聯網
上載者:User

Chapter 2 Data Types and Variables

1.       VARIABLE AND BASEIC DATATYPES

As a programmer, you will frequently wantyour program to “remember” a value. For example, if your program requests avalue form the user, or if it calculates a value, you will want to remember itsomewhere so you can use it later. The way your program remembers things is byusing variables. For example:

Int b;

This line is to create a variable called bthat is able to hold one integer value.

A variable has a name(in this case, b) anda type(in this case, int , an integer)

You can store a value in b by sayingsomething like

b=5;

you can use the value in b by sayingsomething like

printf(“%d”, b);

#include <stdio.h>

 

int main()

{

         int  b;

         b  = 5;

         printf("%d",  b);

         return  0;

}

In c, there are several standard types forvariables:

Bool-true or false, typically stored in onebyte.

Int-integer(whole number) values

Float-floating point values

Char- single character value (such as “m”or “Z”)

There are also several variants on thesetypes such as double, unsigned int, long, unsigned long

Type                                                                  size

Char,unsigned char, signed char             1 byte

Short, unsigned short                                  2 bytes

Int, unsigned int                                            4 bytes

Long, unsigned long                                     4 bytes

Float                                                                4bytes

Double                                                            8bytes

 

VariableNames

Every variable has a name and a value. Thename identifies the variable, the value stores data

Every variable name in C must start with aletter, the rest of the name can consist of the letters, numbers and underscorecharacters.

C recognizes upper and lower casecharacters as being different

Finally, you cannot use any of C’s keywordslike mani, while, switch ect as variable names.

Examples of legal variable names include

X                result        outfile       bestyet

X1              x2              out_file    best_yet

Power       impetus   gamman  hi_score

 

Variableinitialization

At compile time in the declaration

e.g   intx = 5;

         charcode = ‘B’;

         inti=0;

at run time by an assignment

         e.gx=5

at run time by an input statement

         e.g.scanf(“%d”, &x);

 

Constants

To define a constant define a “variable”(usually, U.C.) with keyword.

         const

This is how it works:

         Constfloat PI=3.1415926;

This does NOT work:

         Constfloat PI=3.0;

         PI= 3.1415926; /*not allowed to change it*/

#include <stdio.h>

 

int main()

{

         const  float PI = 3.14159;

         PI  = 3.14;

         return  0;

}

Error: assignment of read-only variable ‘PI’

 

#include <stdio.h>

int term; /* term used in two expression  */

int main()

{

         term  = 3 * 5;

         printf("Twice  %d is %d\n", term, 2 * term);

         printf("Three  times %d is %d\n", term, 3 * term);

         return  0;

}

 

Floating Point Versus Integer Divide

The division operator is special, There isvast difference between an integer divide and floating-point an integer divide,the result is truncated (any fractional part is discarded). So the value of19/10 is 1

Expression                 result               result type

1+2                              3                          integer

1.0+2.0                       3.0                      floating point

19/10                          1                          integer

19.0/10.0                            1.0                      floating point

C allows the assignme of an integerexpression to floating-point variable, C will automatically perform theconversion from integer to floating point, a similar conversion is performedwhen a floating-point number is assigned to an integer.

 

For example:

#include <stdio.h>

int integer; /* an integer */

float floating; /* a floating-point  number */

int main()

{

         floating  = 1.0 / 2.0; /* assign "floating" 0.5 */

         printf("%f\n",  floating);

         integer  = 1 / 3; /* assign integer 0 */

         printf("%d\n,  integer");

         integer  = (1 / 2) + (1 / 2); /* assign floating 0 */

         printf("%d\n,  integer");

         floating  = 3.0 / 2.0; /* assign floating 1.5 */

         printf("%f\n",  floating);

         integer  = floating; /* assign integer 1 */

         printf("%d\n,  integer");

         return  0;

}

 

Why is an incorrect result printed?

#include <stdio.h>

float result; /* result of the divide */

 

int main()

{

         restult  = 7.0 / 22.0;

         printf("the  result is %d\n", result);

         return  0;

}

 

Exercise 1

Write a program to computer the area andperimeter of a rectangle with a width of 3 inches and a height of 5 inches. Whatchanges must be made to the program so that it works fo a rectangle with awidth of 6.8 inches and a length of 2.3 inches.

 

Exercise 2

Write a program that deliberately makes thefollowing mistakes;

Prints a floating-point number using the %dconversion.

Prints an integer using the %f conversion.

Prints a character using the %d conversion.

 

2Enumeration types

An enumeration type is a distinct integertype with enumerators representing integer values starting from 0.  The integer value of an enumerator can alsobe assigned explicitly. An enumeration type can be identified by an optionaltag name.  the declaration of enumerationtypes and variables are as in the following examples;

Enum suit{clubs, diamons, hearts, spades};//clubs=0, diamonds=1, hearts=2, spades=3

Enum suit card; //a variable of type suit

Enum Boolean{false, true, uncertain = -1}a, b; // define two variables a and b

A = false;

B=uncertain

Enum{a=6, b,c=3,d=2*b} x,y;

a=6,b=7,c=3,d=14

#include <stdio.h>

 

int main( int argc, char *argv[] )

{

         enum  suit{clubs, diamonds, hearts, spades};

         //clubs  = 0, diamonds = 1, hearts = 2, spades = 3

         enum  suit card; // a variable of type suit

         card  = diamonds;

         if(card  == clubs)

         {

                   printf("clubs  is selected!\n");

         }

         else  if(card == diamonds)

         {

                   printf("diamonds  is selected!\n");

         }

         else  if(card == hearts)

         {

                   printf("hearts  is selected!\n");

         }

         else

         {

                   printf("spades  is selected!\n");

         }

         return  0;

}

 

#include <stdio.h>

 

int main()

{

         enum  WEEKDAY {Sunday, Monday, Tuesday, Wednsday, Thursday, Friday, Saturday};

         enum  WEEKDAY today; // a variable of type WEEKDAY

         int  val = 0;

         scanf("%d",  &val);

         today  = val;

         if(today  == Sunday)

         {

                   printf("I  am going to travel!\n");

         }

         else  if(today == Monday)

         {

                   printf("This  is Monday\n");

         }

         else

         {

                   printf("Test  today\n");

         }

         return  0;

}

 

3array types

An array lets you declare and work with acollection of values of the same type.

For example, you might want to create acollection of five integers, one way to do it would be declare five integers directly:int a, b, c,d ,e

This is of, but what if you needed athousand integers?

An easier way is to declare an array offive integers: int a[5];

The five separate integers inside thisarray are accessed by an index, all arrays start at index zero an go to n-1 in C,thus , int a[5]; contains five elements. For example:

Int a[5]; a[0]=12; a[1]=9; a[2]=14; a[3]=5;a[4]=1;

Example: computes the total an average offive numbers

 

#include <stdio.h>

 

float data[5]; /* data to average and  total */

float total; /* the total of the data  items */

float average; /* average of the item */

int main()

{

         data[0]  = 34.0;

         data[1]  = 27.0;

         data[2]  = 45.0;

         data[3]  = 82.0;

         data[4]  = 22.0;

         total  = data[0] + data[1] + data[2] + data[3] + data[4];

         avarage  = toatal / 5.0;

         printf("Total  %f Avarage %f\n", total, avarage);

         return  0;

}

This program output

Total 210.000000 Avarage 42.000000

 

Example3

#include <stdio.h>

 

int main()

{

         int  a[5];

         int  i;

         for(i  = 0; i < 5; i ++)

         {

                   a[i]  = i;

         }

         for(i  = 0;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.