【发布时间】:2016-02-01 01:28:05
【问题描述】:
我已经学习 C 一个星期了。今天学习了数组以及如何使用冒泡排序对它们进行排序,所以我按照书中的代码编写了一些代码,它单独运行很好,但它不适用于更大的程序,只会跳过循环。我试图调试它,直到第 20 行,由于某种原因,外部将立即等于 9,因此内部将等于 10,程序将继续运行。这是我的代码:
#include <stdio.h>
int main(void) {
int ctr; //loop counter
int idSearch; //Customer to look for (the key)
int found = 0; // 1 (true) if the customer is found
/* Defines the 10 elements in each of the parallel arrays */
int custID[10] = {313, 454, 502, 101, 892, 475, 792, 912, 343, 644};
float custBal[10] = {0.00, 45.43, 71.23, 301.56, 9.08, 192.41, 389.00, 229.67,
18.31, 59.54};
int tempID, inner, outer; // For sorting float temBal
tempID = inner = outer = 0;
float tempBal =0;
/* first, sort the arrays by customer ID */
for (outer=0; outer < 9; outer++);
{
for (inner = (outer+1); inner < 10; inner++)
{
if (custID[inner] < custID[outer])
{
tempID = custID[inner]; // must switch both arrays
tempBal = custBal[inner]; // or they won't be linked
custID[inner] = custID[outer];
custBal[inner] = custBal[outer];
custID[outer] = tempID;
custBal[outer] = tempBal;
}
}
}
/* Interact with the user looking to find a balance */
printf("**Customer Balance Lookup**\n");
printf("What is the customer's number? ");
scanf(" %d", &idSearch);
/* Now look for the ID in the array */
for (ctr = 0; ctr <10; ctr++)
{
if (idSearch == custID[ctr]) //Do they match?
{
found = 1; // Yes, match flag is set to True
break;
}
if (custID[ctr] > idSearch) // No need to keep searching
{
break;
}
}
// Once the loop has completed, the ID was either found if not
if (found)
{
if (custBal[ctr] > 100)
{
printf("\n**That customer's balance is $%.2f.**\n", custBal[ctr]);
printf("No additional credit\n");
} else {
printf("\n**The customer's balance is good!**");
}
}else { printf("\n**You have entered an incorrect customer ID.**");
printf("\n ID %d was not found in the list.\n", idSearch);
}
return (0);
}
【问题讨论】:
-
发布
custID[]和custBal[]的声明。 -
@chux 你能解释一下吗?我很新,所以我不明白你想说什么。
-
发布的代码缺少变量
custID[], custBal[], tempID , tempBal, outer的声明。将它们作为您问题的一部分发布。当前的代码按原样肯定不会编译。 -
第 3 行是
int main(void) {。请正确识别出错的行。 -
去掉这一行的分号:
for (outer=0; outer < 9; outer++);。分号是循环正在执行的语句,而不是后面的块。在这一行设置断点应该可以很快识别出错误。