我一直在学习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);
}
答案 0 :(得分:2)
您似乎尝试对custID
数组进行冒泡排序,并在此过程中对custBal
数组进行排序。但是,您进行冒泡排序的逻辑是错综复杂的。请尝试使用此双for
循环:
for (outer = 0; outer < ( n - 1 ); outer++) {
for (d=inner = 0; inner < n - outer - 1; inner++) {
if (custID[inner] > custID[inner+1])
{
tempID = custID[inner];
tempBal = custBal[inner];
custID[inner] = custID[inner+1];
custBal[inner] = custBal[inner+1];
custID[inner+1] = tempID;
custBal[inner+1] = tempBal;
}
}
}
答案 1 :(得分:0)
我写这篇文章真的很尴尬,但是经过30分钟查看我的代码,逐行查看,我在第20行的末尾找到了一个半冒号for (outer=0; outer < 9; outer++);
谢谢你们试图帮助我,我真的很感激。