如果试图在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;}
}
有几个问题,“找到的”变量超出了if语句之外的范围,因此我不能在if语句之外执行printf部分,否则它只会打印“ [number]不是一个完美的正方形数十次。我怎样才能做到这一点?我花了几个小时解决这个问题。
您显示的代码非常耗时,因为如果数字为999,则需要迭代数千次。
使用sqrt()
函数frommath.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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句