我正在尝试解决两个不同的C问题,并希望获得一些帮助和建议,以便更好地了解C的工作原理以及我是否正确地使用这些问题。
第一个问题是:编写一个函数,该函数计算值(x)在数组的第一个(n)元素中出现的次数,并将该计数作为theArray中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(x x x * x ....)。任何帮助和建议将不胜感激!
答案 0 :(得分:3)
在第一个问题中,您将数组后面的元素作为函数的参数。
定义一个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++;