[英]I want to make a program in C which takes an array as an input and tells which number are perfect squares
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c.我是编码新手,目前正在学习 c。 I came up with this code but it doesn't work can someone tell me what is the problem with this code?
我想出了这段代码,但它不起作用有人能告诉我这段代码有什么问题吗?
There are a couple of issues with this exercise, but generally you're on the right track.这个练习有几个问题,但通常你在正确的轨道上。 Here, a version of your example with some possible corrections :
在这里,您的示例版本有一些可能的更正:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:一些提示:
Arrays, that have an unknown size at compile time are usually allocated with malloc()
, and must be deallocated again with free()
(see also: alloca()
, calloc()
, realloc()
). Arrays,在编译时大小未知的通常使用
malloc()
分配,并且必须使用free()
再次释放(另请参见: alloca()
, calloc()
, realloc()
)。 (In "more recent versions of C" there is also the possibility to use variable length arrays , but those can limit the portability of the code). (在“更新的 C 版本”中,也可以使用可变长度 arrays ,但这些会限制代码的可移植性)。
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.始终确保检查 for 循环的开始值和结束条件,以防止越界错误。
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.并尝试一致地格式化代码,使用良好的名称和良好的缩进来提高读取、维护、重用性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.