【发布时间】:2017-03-07 06:45:04
【问题描述】:
我正在尝试解决两个不同的 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 循环 (xxx*x....)。任何帮助和建议将不胜感激!
【问题讨论】:
-
count = count++;-->count++; -
long int theArray[SIZE] = {-->int theArray[SIZE] = { -
你没有计算
x出现在像27这样的数字中的次数。您需要将每个元素发送到一个新函数,将数字转换为数字,然后检查x是否在数字中,返回它出现的次数。 -
下次有两个问题请提出两个问题。否则,您的结果将无法轻松搜索。而且它不适合问答形式,因为您可能会得到两个单独的答案,每个答案都解决一个问题。
-
@CodeMonkey true.. 我在看
n=7并错误地认为他在寻找 7。
标签: c