我有一个我一直在做的任务。我的代码似乎具有正确的数学运算和正确的顺序(至少按顺序),但我的答案有点古怪。我根据我的输入值正确地获得了每个问题的部分内容,但随着输入值的变化,我永远不会得到相同的部分。是否有一些关于我缺少的 C 操作顺序导致了这种情况?
我觉得问题出在
intPeople = intCarCounter * intTrainCounter * CAR_CAPACITY;
对于样本运行#3,前两个输入有 120 人(正好比正确答案多 20 人),剩余人数应该是样本运行#4 中的人数。在第三个输入中,我得到 112 人,这又是样本运行 #4 的正确答案。最后,在第 4 次样本运行中,我得到了 128 人(比正确答案多 16 人),剩余人数应该在第 3 次样本运行中。有任何想法吗?
作业: http ://cop3223.blogspot.com/2013/01/problem-c-roller-coaster-design-coasterc.html
我的代码:
#include <stdio.h>
#include <stdlib.h>
#define FIRST_CAR_LENGTH 10
#define NORMAL_CAR_LENGTH 8
#define CAR_CAPACITY 4
int main(void)
{
/* Initialize Variables */
int intTrack,intMaxTrainSize,intActualTrainSize,intPeople,intCarCounter,intTrainCounter,n;
/* Ask user for value of N */
printf("What is the value for N?> ");
scanf("%d",&n);
for (int i=0; i<n;i++)
{
/* Ask user for total length of track */
printf("\nWhat is the total length of the track, in feet?> ");
scanf("%d",&intTrack);
/* Ask user for maximum length of each train */
printf("What is the maximum length of a train, in feet?> ");
scanf("%d",&intMaxTrainSize);
/* Set/Reset initial values of intActualTrainSize, intCarCounter and intTrainCounter */
/* Each train will begin with FIRST_CAR_LENGTH -> intActualTrainSize=FIRST_CAR_LENGTH */
/* Each train will begin with 1 car -> intCarCounter=1 */
/* Train counter will begin at 0 -> intTrainCounter=0 */
intActualTrainSize=FIRST_CAR_LENGTH;
intCarCounter=1;
intTrainCounter=0;
/* Continue to add additional cars using NORMAL_CAR_LENGTH until the maximum train size has been reached */
/* Count how many NORMAL_CAR_LENGTH cars are added -> intCarCounter++*/
while (intActualTrainSize < intMaxTrainSize)
{
intActualTrainSize=intActualTrainSize+NORMAL_CAR_LENGTH;
intCarCounter++;
}
/* Count how many trains can be added until 25% of the track is used up -> intTrainCounter++ */
while (intTrainCounter*intActualTrainSize < (int)(intTrack*.25))
{
intTrainCounter++;
}
/* Count how many people can be on the track at one time -> intPeople = intCarCounter * intTrainCounter * CAR_CAPACITY */
intPeople = intCarCounter * intTrainCounter * CAR_CAPACITY;
printf("\nYour ride can have at most %d people on it at one time.",intPeople);
if (intActualTrainSize>intMaxTrainSize)
printf("\nMaximum Train Length has surplus of %d feet.\n",intActualTrainSize-intMaxTrainSize);
else if (intMaxTrainSize==intActualTrainSize)
printf("\nMaximum Length fits exactly.\n");
}
system("pause");
return 0;
}