c - 如果在数组中找到元素,则尝试打印一件事,如果在 C 中的数组中不存在,则尝试打印其他内容

标签 c arrays

如果在 for 循环中找到某个元素,我将尝试打印一件事,如果找不到则打印其他内容。这应该很简单,但我尝试了很多不同的方法,但似乎都不起作用。

int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;
int found = 0;
int number = 100;

for (; i<numberOfSquares; i++)
{
    squaresArray[i] = i*i;
    if (number==squaresArray[i])
    {
        found = 1;
    }
            if (found == 1){
                printf("%d is a perfect square", number); 
                break;}
            else {
                printf("%d is not a perfect square", number);
                break;} 
    }

有几个问题,“found”变量超出了 if 语句的范围,所以我不能在 if 语句之外执行 printf 部分,或者它只是打印“[number] is not一个完美的正方形”几十次。我怎样才能做到这一点?我在这个问题上花了几个小时。

最佳答案

您显示的代码非常耗时,因为如果数字是 999 的平方,您需要迭代数千次。

使用sqrt() math.h 中用于查找给定数字是否为完美平方的函数

试试这个。

double param = 1024.0; //read different inputs with the help of scanf(). 
int i;

if ( ( (  i= (int) (sqrt(param)*10)  ) % 10) == 0 )  

      printf(" is a perfect square");
else
      printf(" is not a perfect square");

来自@jongware 的评论,这比上面的更棘手,也更容易理解。

   if ( ((int)sqrt(param))*((int)sqrt(param))==param)  

          printf(" is a perfect square");
    else
          printf(" is not a perfect square");     

关于c - 如果在数组中找到元素,则尝试打印一件事,如果在 C 中的数组中不存在,则尝试打印其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203619/

相关文章:

c - C 中的方阵求逆

c - 如何通过丢弃重复元素在数组中查找一系列唯一数字

c - gcc 编译器中是否有用于 pthread 代码的标志以最小化执行时间?

c - 检测 FFmpeg 是否正在运行或已停止运行

c - C 中的数组 - 最后一个元素分配索引值

c++ - 如何在 C++11 中创建线程对象数组?

对象数组和 indexOf 的 Javascript 奇怪之处

仅在调试时正确输出

java - 如何创建一个 int 数组,其中包含给定范围内随机打乱的数字

C 编程问题