[C语言]变量VS常量

时间:2023-03-09 05:24:58
[C语言]变量VS常量

--------------------------------------------------------------------------------------------

1. 固定不变的数是常数,直接写在程序里称为直接量(literal)。

  int total = 100 - price;

#include <stdio.sh>

int main()
{
int price = ;       //初始化 printf("请输入金额:");
scanf("%d", &price); //注意别忘了取地址符 int change = - price; printf("找您%d元", change);
}

2. 回过头来我们并不知道上面的100是什么数,为了方便我们辨识,这里使用一个常量。

  const修饰符加在int前面用来表示常量,用const定义的属性,一旦初始化,不能被修改(PHP5也是如此); 如果对常量进行修改赋值,编译器将报错(Read-only variable is not assignable),对常量约定使用大写。

   

  const int AMOUNT = 100;

  int change = AMOUNT - price;

const int AMOUNT = ;

int price = ;

printf("请输入金额:");
scanf("%d", &price); int change = AMOUNT - price; printf("找您%d元", change);

3. 现在不想定义常量,那么使用多个scanf

  

int amount;  //未初始化

int price;

/*
printf("请输入两个整数:");
scanf("%d %d", &amount, &price); //两个数以空格或回车隔开;注意:遇到非数值输入 如字符串时,scanf将出错,内存里有什么就取什么
printf("%d + %d = %d", amount, price, amount + price);
*/
prinf("请输入票面:");
scanf("%d", &amount); printf("请输入金额:");
scanf("%d", &price); int change = amount - price;

if(change > 0) {
  printf("找您%d元", change); 
} else {
  printf("您的钱不够!\n");
}

Link:http://www.cnblogs.com/farwish/p/4167669.html