【问题标题】:Trouble creating an if else program for calculating different parking cost for different vehicles创建用于计算不同车辆的不同停车费用的 if else 程序时遇到问题
【发布时间】:2015-03-22 18:19:56
【问题描述】:

我无法使此代码正常工作。我刚刚学习了这个内容(if else 语句),并且必须通过创建一个计算每个不同车辆的停车成本的程序来实现它。 c 用于汽车(每小时 2 美元),b 用于公共汽车(每小时 3 美元),t 用于卡车(每小时 4 美元)。这是在使用 dev-c++ 编译器的 c 编程中。

感谢所有反馈,提前感谢您!

#include <stdio.h>

//declaration
char parkingCharge (int pc);
int pc;
int h, total, c, b, t;
char v;

int main (void)
{	
//statements

	printf ("Enter type of vehicle (c for car, ");
	printf ("b for bus, or t for truck): ");
	scanf ("%c", &v);
	
	printf ("How long did you park: ");
	scanf ("%d", &h);
	
	total = pc;
	printf ("Your total is: %d", total);

return 0;
}

char parkingCharge (int pc)
{
//statements

	if (v == c){
	   pc = 2 * h;
    }
    else if (v == b){
	   pc = 3 * h;
    }
    else if (v == t){
	   pc = 4 * h;
    }
return total;
}

【问题讨论】:

  • parkingCharge 应该可能返回一个 int(速率和时间的乘积)
  • 感谢您的回复!我不明白你的意思。我对编程相当陌生。 pc等于产品费率和时间,不是吗?
  • 你甚至不打电话给parkingCharge(),但如果你打电话了,你对变量的使用就无处不在了。

标签: c dev-c++


【解决方案1】:
#include <stdio.h>

//declaration
int parkingCharge (char v, int h);
int h;
char v;

int main (void)
{
//statements

        printf ("Enter type of vehicle (c for car, ");
        printf ("b for bus, or t for truck): ");
        scanf ("%c", &v);

        printf ("How long did you park: ");
        scanf ("%d", &h);
        // You forgot to call the function parkingCharge.
        int total = parkingCharge(v, h);
        printf ("Your total is: %d\n", total);

return 0;
}
// parkingCharge should return an int value and you could pass
// v and h as parameters.
int parkingCharge (char v, int h)
{
    int pc;
    // Remember when you compare a variable with a constant char, you
    // put the constant char value between ''.
    if (v == 'c'){
           pc = 2 * h;
    }
    else if (v == 'b'){
           pc = 3 * h;
    }
    else if (v == 't'){
           pc = 4 * h;
    }
    return pc;
}

【讨论】:

  • ...如果车辆是'k'?
  • 你只需要再做一个 if。像:否则 if (v == 'k') {...}。 :)
  • 不,需要!要么,要么初始化pc
  • 啊。我原以为parkingCharge 是char,而int 是pc。我也忘记了变量的''。我也不明白为什么 char v 和 int h 在这个 'int parkCharge (char v, int h);'我不是在质疑你的答案,只是我个人不明白。我正在从一本书中学习编程,其中一些内容非常笼统,没有详细介绍。
  • @WeatherVane:您将“k”视为预期值还是意外值?
猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多