繁体   English   中英

程序编译但没有给出正确的值

[英]Program compiles but does not give correct value

我正在为我的C编程类编写一个卡路里程序,但在编译时我没有得到正确的输出。 例如,我输入的卡路里数为385,并且获得的芯片总数超过了我最初输入的卡路里数。 我已包含以下代码。

任何帮助将不胜感激。

#include "stdafx.h"

void calories(int total, int*pizza, int*chips, int*apple, int*mustard)

{
if (total >= 385)
    *pizza = (total - 385);
if (total >= 170)
    *chips = (total - (*pizza * 385))/170;
if (total >= 80)
    *apple = (total - (*pizza * 385) - (*chips * 170)) / 80;
if (total >= 5)
    *mustard = (total - (*pizza * 385) - (*chips * 170) - (*apple * 80)) / 5;

return;
}

int main(void)

{

int total, pizza, chips, apple, mustard;

printf("Enter the total whole number of calories you would like to eat for your meal: ");
scanf_s("%d", &total);
calories(total, &pizza, &chips, &apple, &mustard);
printf("\n Total= %d", total);
printf("\nSlices of pizza= %d", chips);
printf("\nBags of chips= %d", pizza);
printf("\nSlices of apple= %d",apple);
printf("\nTeaspoons of mustard= %d", mustard);

return 0;
}

为了详细说明@EdHeal的评论,您要在堆栈中声明变量pizza, chips, apple, mustard C中的堆栈变量不会自动设置为零。 您必须自己将它们初始化为某个值。

您将变量的地址传递给calories()函数,但是在该函数内部, 除非卡路里计数大于某个数字, 否则您不会为变量分配值。 因此,每当卡路里计数“太低”时,变量中就会有随机值。

最简单的解决方案是在声明时初始化变量:

int pizza = 0, chips = 0, apple = 0, mustard = 0;

一个不太简单但实际上更好的主意是在calorie函数中的语句中添加else子句,如果没有其他值,则将目标值设置为零:

if (total >= 385)
    *pizza = total / 385;
else
    *pizza = 0;

/* etc ... */

在每个if语句中,您要询问total是否更大,但是您并未降低total的价值……看起来您想处理多个比萨饼,依此类推,但您并未定义if问题以适应这种可能性

*pizza = total % 384;
total -= *pizza * 384;

*chips = total % 170;
total -= *chips * 170;

... do similar here for next purchase ...
... etc 

printf语句中的错误:

printf("\nSlices of pizza= %d", chips);
printf("\nBags of chips= %d", pizza);

对于比萨饼的印刷,您赋予了薯片价值,反之亦然。

if (total >= 385)
    *pizza = (total - 385);

高于您的总和除以385,可能会导致错误的结果。

希望这会有所帮助。

我认为这是您应该采用的模式

if (total >= 385) {
   *pizza = total / 385;
   total = total - *pizza * 385;
}
if (total >= 170) {
   *chips = total/170;
   total = total - *chips * 170;
}

etc...

即保持总计运行总计

PS:您真的应该更好地饮食

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM