问答详情
源自:5-14 综合练习

资料下载的demo里最后判断总数是不是有问题

#include <stdio.h>
double getTaxiPrice(int hours,int distance)
{
	double totalPrice = 0.0;	//定义打车费用 
	double perPrice = 2.3;	//定义每公里单价计费 
	int startPrice = 13;	//定义起步价 

	if(hours<0 || hours>24){
		printf("请填写正确的时间\n");
		return 0;
	}
	else if(!(hours>=5 && hours<23))	//判断打车时间是否要增加费用
	{
		perPrice *= 1.2;	//费用增加20%                         
	}
	if(distance >3)		//判断公里数
	{
		totalPrice = startPrice +(distance - 3)*perPrice;	//计算价钱
	}
	else
	{
		totalPrice = startPrice;    
	}
	totalPrice++;	//加一块钱的燃油费
	return totalPrice;
}
int main()
{
	int moring = 9;	//定义上午打车时间
	int afternoon = 18;	//定义下午打车时间
	int distance = 12;	//定义打车公里数
	double totalPrice = 0;	//定义总费用
	if(getTaxiPrice(moring,distance) != 0)	printf("小明每天打车的总费用是:%.2f\n",totalPrice);	//输出
	return 0;    
}

在最后的

	if(getTaxiPrice(moring,distance) != 0)	{
		totalPrice = getTaxiPrice(moring,distance);	//调用计算费用的函数
	} 
	else
	{
		totalPrice += getTaxiPrice(afternoon,distance);	//调用计算费用的函数
	}

这里,先使用if判断早晨出门打车的 钱是否不等于,经过判断是不等于零,于是执行

totalPrice = getTaxiPrice(moring,distance);	

然后后面的

	else if(totalPrice != 0)

这一句按理说就不会执行了吧,因为之前的if语句已经判断为真 了。这样下来就只判断了if中早晨出门的钱,而没有判断晚上回家的钱。所以我认为应该吧else if换成if。也就是将demo中换为两个独立的if条件句

求大神看一下我的理解对么?

提问者:Libra_x 2018-07-29 18:29

个回答

  • 修裾欲溯空
    2018-07-31 10:49:24

    /*
    怎么说呢...这个题目给出了具体的上班时间和下班时间,所以你把它当做一个基本的数学题就好了,没有必要写一
    大串代码,如果变量的值不确定的话,你就一定要用if...else if...这个语句了
    */
    #include <stdio.h>
    int main()
    {
        double s;
        s=13+2.3*(12-3)+1;
        printf("%f",s*2);
        return 0;
    }


  • 修裾欲溯空
    2018-07-30 16:59:54

    你的代码主要有以下的一些问题:1.主函数中并没有调用你自己写的函数,2.明明一个简单的数学题为什么写这么多的代码?

  • 修裾欲溯空
    2018-07-30 16:53:59

    我运行了一下发现你的代码结果输出为0...