您的位置:首页 > 编程语言 > C语言/C++

[C语言]变量VS常量

2014-12-16 17:39 239 查看
--------------------------------------------------------------------------------------------

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

  int total = 100 - price;

#include <stdio.sh>

int main()
{
int price = 0;       //初始化

printf("请输入金额:");
scanf("%d", &price);     //注意别忘了取地址符

int change = 100 - 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 = 100;

int price = 0;

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:/article/5289402.html

@黑眼诗人 <www.Farwish.com>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: