【问题标题】:Finding frequency of an integer in an array and calculating x to the nth power查找数组中整数的频率并计算 x 的 n 次方
【发布时间】: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


【解决方案1】:

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

您定义了一个 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++;

【讨论】:

  • 这应该是一条评论。
  • 我不明白为什么他的问题的解决方案不应该是一个答案。他提出两个不同的问题是问题中的问题,而不是我的答案的问题。
  • 因为您在 EDITING 之前的第一个答案只修复了他的代码中的一个错误。不是一个完整的答案。现在好多了。
  • @CodeMonkey 我不知道 count = count++;是多余的,下次我会尽量记住,运行时错误已修复,谢谢!
  • @TonyTannous 在编辑之前,它是使其工作的最低要求。在(现在 2 次)编辑中,我添加了一件不必要的事情,以及一件可能会根据您的平台引起问题的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多