关于C语言if语句中花括号{}的使用区别?请指点一下

(1)加花括号的程序
#include <stdio.h>

void main()
{
double unit_price = 5.0;
long quantity = 0L;
double discount = 0.0;

printf("\nEnter the number that you want to buy:");
scanf("%ld",&quantity);

if(quantity > 30 && quantity < 50)
{
discount = 0.1;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price* quantity *(1.0 - discount));
}

if(quantity > 50)
{
discount = 0.15;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));
}

if(quantity > 0 && quantity < 30)
{
discount = 0.0;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));
}
getch();

}

(2)不加花括号的程序
#include <stdio.h>

void main()
{
double unit_price = 5.0;
long quantity = 0L;
double total_price = 0.0;
double discount1 = 0.1;
double discount2 = 0.15;
double discount3 = 0.0;

printf("\nEnter the number that you want to buy:");
scanf("%ld",&quantity);

if(quantity > 30 && quantity < 50)
printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount1));

if(quantity > 50)
printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount2));

if(quantity > 0 && quantity < 30)
printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount3));
getch();

}

我想问一下这俩个程序都是一样的结果 为什么第1个程序IF语句中要加花括号而第2个程序IF语句中就不用加花括号呢?区别在哪?

第1个回答  2019-01-05
if条件下要执行多个语句(使用了;就算一句)就要加括号括起,只执行一句就不用加
第2个回答  2008-08-19
你没看清楚呀,呵呵,下面的if只有一个分号;其它的是,说明只有一句

上面的if,有好多分号;说明有好几句,{里面代表的是一个整体,如果只有一个分号,要不要这个花括号都一样的,}
如果一成的将{}去了,其它的不变,结果就不一样了
第3个回答  2008-08-19
因为下边的程序if后面只有打印这一句,上边的程序还有一个赋值,下边的你加上括号也没问题
if语句默认是约束离它最近的语句,要是很多句,就用{}
呵呵
第4个回答  2008-08-19
呵呵~因为if默认的是循序第一句的语句,如果是两句或以上就要用大括号啦~~~~
第5个回答  2008-08-19
简单地说,用花括号括起来的代码块是一个整体,在运行的时候就像一条语句一样执行下来。

if执行的时候会执行到它后面的第一个分号为止,也就是说,它只执行一条语句,除非你用花括号把后面的一串语句括起来变成一条语句。

以上。
喜欢简单的老狼本回答被提问者采纳
相似回答