[英]How do I only make a printf statement appear if the statement is true?
如果包裹重量超过50磅,我将制造一个运输计算器,则无法运输包裹。 我只想在包装重量超过50磅时才显示一个声明,但是无论如何看起来都没有。
我尝试了它作为else语句,if语句和if else语句。
main(){
double distance, weight, weightCharges, shippingCharge, distanceCharge, unableToShip;
printf ("Enter the weight of the package:\n");
scanf ("%lf", &weight);
printf ("Enter the distance your package needs to go: \n");
scanf ("%lf", &distance);
if (weight <= 10)
weightCharges = weight * 3.00;
else
if (weight <= 50)
weightCharges = weight * 5.00;
else (weight > 50);
weightCharges= 0;
if (distance > 1000)
distanceCharge = weightCharges + 10;
shippingCharge = weightCharges + distanceCharge;
unableToShip = weight > 50;
printf ("Your total cost is: %.2lf \n", shippingCharge);
printf ("We're unable to ship your package \n", unableToShip);
}
我希望仅当我们无法运送其包装时才会出现第二个printf,但是无论如何它都会出现。
您是否尝试放置一些if-else语句?
int main()
{
double distance, weight, weightCharges, shippingCharge, distanceCharge; // no need for unableToShip;
printf ("Enter the weight of the package:\n");
scanf ("%lf", &weight);
printf ("Enter the distance your package needs to go: \n");
scanf ("%lf", &distance);
if (weight <= 10)
weightCharges = weight * 3.00;
else
if (weight <= 50)
weightCharges = weight * 5.00;
else (weight > 50);
weightCharges= 0;
if (distance > 1000)
distanceCharge = weightCharges + 10;
shippingCharge = weightCharges + distanceCharge;
//unableToShip = ;
printf ("Your total cost is: %.2lf \n", shippingCharge);
if(weight > 50)
printf ("We're unable to ship your package \n");
}
if
在这里的工作方式与其他地方相同:
if (unableToShip)
printf ("We're unable to ship your package\n");
int main(){
double distance, weight, weightCharges, shippingCharge, distanceCharge, unableToShip;
printf ("Enter the weight of the package:\n");
scanf ("%lf", &weight);
printf ("Enter the distance your package needs to go: \n");
scanf ("%lf", &distance);
if (weight <= 20)
weightCharges = weight * 5.00;
else
if (weight <= 100)
weightCharges = weight * 10.00;
else (weight > 100);
weightCharges= 0;
if (distance > 1000)
distanceCharge = weightCharges + 20;
shippingCharge = weightCharges + distanceCharge;
unableToShip = weight > 100;
printf ("Your total cost is: %.2lf \n", shippingCharge);
printf ("We're unable to ship your package \n", unableToShip);
}
首先, unableToShip
应该为int
或bool
类型(如果您使用的是最新且支持<stdbool.h>
的编译器)。 double
在这种情况下并不能很好地工作。
其次,即使unableToShip
是布尔条件的正确类型,将其作为参数传递给printf
也不会使printf
有条件地工作。 如果您有格式字符串可以接受,那么它将成为格式化输出的一部分。 您需要准备的是if (unableToShip)
后跟printf
语句。
第三,如果要打印的字符串不包含任何格式并以新行结尾,则应使用puts
而不是printf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.