不知道为什么不能在数组中找到值。每当我运行代码时,它都会返回“在大海捞针中找不到针头”。
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
//Makes sure the input value is positive
while (n > 0)
{
//Searches until value is found
for (int i = 0; i < n; i++)
{
if (value == values[i])
{
printf("Found it!\n");
return true;
}
}
}
return false;
}
还没开始排序
/**
* Sorts array of n values.
*/
/*void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
return;
}*/
我已经更改了它,并按原样使用了if语句,但仍给出相同的结果。
#include <cs50.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
/* if (n >= 0)
{
return false;
}*/
for (int i = 0; i < n; i++)
{
if (value == values[i])
{
printf("Found it!\n");
return true;
}
}
return false;
}
问题已解决!似乎我不小心在文件夹外制作了另一个同名文件。我正在更改错误的文件!!!
最佳答案
问题是这部分:
while (n > 0)
这使您陷入无尽的循环。
您应该将其替换为if语句:
if(n<=0){
return false;
}
关于c - CS50 helpers.c,代码找不到值(value)(针)?有任何想法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32859664/