【发布时间】:2016-02-27 11:59:17
【问题描述】:
我的函数countCopies 无法正常工作,即使它获得了正确的输入。它所要做的就是将一个整数数组作为输入,然后在这个数组中搜索第二个输入 x 的重复项。
int main() {
char intArray[100]; //The integer array can only hold 100 integers
int i, x, j;
printf("Please enter a couple of integers and when you're done enter end. ");
i = 0;
while (scanf("%d", &intArray[i++]) == 1)
/*empty loop*/;
scanf("%*s");
printf("Enter x:");
scanf("%d", &x);
printf("Copies = %d\n", countCopies(intArray, i, x));
}
int countCopies(int a[], int n, int x) {
int count = 0;
int j = 0;
for (j = 0; j < n - 1; j++) {
if (a[j] == x) {
count++;
}
}
return count;
}
【问题讨论】:
-
将
j < n - 1更改为j < n -
为什么是
scanf("%*s");?? -
@AshishAhuja 我知道这意味着什么,但我很困惑为什么在这里使用它(我看不出有任何理由在这里使用它。)
-
@ameyCU:看我的回答:
scanf("%*s");跳过了end字。与往常一样,不明显的代码应该被注释掉。
标签: c