关于C语言if语句中花括号{}的使用区别?(1)加花括号的程序#include 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(q
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/08 10:57:05
关于C语言if语句中花括号{}的使用区别?(1)加花括号的程序#include 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(q
关于C语言if语句中花括号{}的使用区别?
(1)加花括号的程序
#include
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
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语句中就不用加花括号呢?区别在哪?
关于C语言if语句中花括号{}的使用区别?(1)加花括号的程序#include 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(q
简单地说,用花括号括起来的代码块是一个整体,在运行的时候就像一条语句一样执行下来.
if执行的时候会执行到它后面的第一个分号为止,也就是说,它只执行一条语句,除非你用花括号把后面的一串语句括起来变成一条语句.
以上.
喜欢简单的老狼