gpt4 book ai didi

c - 查找数组中整数的频率并计算 x 的 n 次方

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:13 25 4
gpt4 key购买 nike

我正在尝试解决两个不同的 C 问题,并希望得到一些帮助和建议,以便更好地理解 C 的工作原理以及我是否在正确的轨道上解决这些问题。

第一个问题是:编写一个函数来计算值 (x) 在数组的前 (n) 个元素中出现的次数,并将该计数作为 x 在数组中出现的频率返回。因此,举个例子,如果传递的数组包含值 {5, 7, 23, 8, 23, 67, 23}。 n 为 7,x 为 23,那么它将返回值 3,因为 23 在数组的前 7 个元素中出现了 3 次。

这是我目前所拥有的:

#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */

int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;

for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}


int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};

numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);

return 0;
}

目前我收到一条运行时错误消息,我认为它与 for 循环函数有关。

第二个问题是:编写一个函数,计算一个整数的正整数次方。让函数返回一个long int,它表示计算x的n次方的结果。不要使用C pow库函数,不要使用递归!

到目前为止我的代码:

#include <stdio.h>

int x_to_the_n (int x, int n)
{
int i;
long int result = 1;

if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}

return (result);
}

int main(void)
{
int x =4;
int n =5;
long int result;

result = x_to_the_n (x, n);

printf ("%i", result);
return 0;
}

我不能使用递归,所以这是不可能的。所以,我认为下一个最好的方法是 for 循环。但是我对如何根据 (n) 的值进行 for 循环 do (xxx*x....) 有点困惑。任何帮助和建议将不胜感激!

最佳答案

在第一个问题中,您将数组后面的一个元素作为函数的参数。

您定义了一个 long int 数组,并将其传递给需要 int 数组的函数。

long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};

应该是

int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};

取而代之的是:

numberFrequency = frequency (theArray[SIZE], n, x);

试试这个:

numberFrequency = frequency (theArray, n, x);

并替换:

count = count++;

与:

count++;

关于c - 查找数组中整数的频率并计算 x 的 n 次方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42641892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com