如果在 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/