C Tutorial/Language/Variable Declaration — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
(нет различий)
|
Текущая версия на 13:32, 25 мая 2010
Содержание
Define three variables and use assignment operator to assign value
<source lang="cpp">int main()
{ int term; /* term used in two expressions */ int term_2; /* twice term */ int term_3; /* three times term */ term = 3 * 5; term_2 = 2 * term; term_3 = 3 * term; return (0); }</source>
How to declare a variable
A variable declaration serves three purposes:
- It defines the name of the variable.
- It defines the type of the variable (integer, real, character, etc.).
- It gives the programmer a description of the variable.
<source lang="cpp">int answer; /* the result of our expression */</source>
- The keyword int tells C that this variable contains an integer value.
- The variable name is answer.
- The semicolon (;) marks the end of the statement.
- The comment is used to define this variable for the programmer.
Initialize int value in declaration
<source lang="cpp">#include <stdio.h> int main(void) {
int number0 = 10, number1 = 40, number2 = 50, number3 = 80, number4 = 10; int number5 = 20, number6 = 30, number7 = 60, number8 = 70, number9 = 110; int sum = number0 + number1+ number2 + number3 + number4+ number5 + number6 + number7 + number8 + number9; float average = (float)sum/10.0f; printf("\nAverage of the ten numbers entered is: %f\n", average); return 0;
}</source>
Average of the ten numbers entered is: 48.000000
Meaningful variable name
<source lang="cpp">int p,q,r;</source>
Use printf to output variable
<source lang="cpp">#include <stdio.h>
int main() { int term; /* term used in two expressions */ term = 3 * 5; printf("Twice %d is %d\n", term, 2*term); printf("Three times %d is %d\n", term, 3*term); return (0); }</source>
Twice 15 is 30 Three times 15 is 45
The number of %d conversions should match the number of expressions.
Using a variable to store value
<source lang="cpp">#include <stdio.h> int main(void) {
int salary; salary = 10000; printf("My salary is %d.", salary); return 0;
}</source>
My salary is 10000.
Variables
- You can store values in variables.
- Each variable is identified by a variable name.
- Each variable has a variable type.
- Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores.
- Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables.
- The variables are defined at the begining of the block.
The following is an example of some variable names:
<source lang="cpp">average /* average of all grades */
pi /* pi to 6 decimal places */ number_of_students /* number students in this class */</source>