簡體   English   中英

編寫函數以檢查其參數(正整數)是否為理想平方。 然后將此函數應用於正整數的向量

[英]Write a function to check if its parameter (positive integer) is a perfect square. Then apply this function to a vector of positive integers

我是新手,現在我正在嘗試了解它們,因此,如果您遇到一些“菜鳥”錯誤,請對我輕松一點。我非常感謝此程序的幫助:

#include <stdio.h>
#include <stdlib.h>

int check(int a[],int n,int i )
{
    int j;
    for (j=0; j<n ; j++)
    {
    if(a[i]==j*j)
        return 1;
    else
        return 0;
    }
}
int main()
{
   int n,a[100],i;
   printf("\nThe size:\n");
   scanf("%d",&n);
   for(i=0; i<n; i++)
   {
    printf("\na[%d]=",i);
    scanf("%d",&a[i]);

    if(check(a,n,i)==1)
        printf("%d is a perfect square\n",a[i]);
    else
        printf("%d is not a perfect square\n",a[i]);

   }


return 0;
}

我成功地使它運行,但是無論輸入(1、4、5、9 ...)都總是打印出來,這是不對的:“不是完美的正方形”

您需要的是僅將數字傳遞給該函數。 為此,您可以簡單地執行以下操作:

int check(int value, int n)
{
    for (int j=0; j<n ; j++)
        if(value==j*j)
            return 1;
    return 0;
}

並像這樣調用函數:

check(a[i], n)

現在,您將不傳遞整個數組,而僅傳遞一個數字,即其第i個數字。

此時,您可以檢查一個數字 考慮一下您需要做什么,以檢查一組數字。 您將如何將check()應用於向量的每個數字?

PS:一個重要且基本的注意事項是您應該縮進代碼 ,因為它會使所有內容都更具可讀性(例如,大括號對齊)。


附錄:

您可以使您的初始函數像這樣工作:

int check(int a[],int n,int i )
{
    int j;
    for (j=0; j<n ; j++)
    {
        if(a[i]==j*j)
            return 1;
    }
    return 0;
}

這樣,當條件不理想時,您就不會停止循環,但也會繼續檢查其他條目。

但是,我強烈建議您使用上面的建議。

編寫函數以檢查其參數(正整數)是否為理想平方

需要的是:

bool check_if_perfect_square(unsigned n);

簡單找到整數平方根 整數平方根例程不太難編寫代碼。 也許:

#include <stdbool.h>

// Square root of t round toward 0
unsigned uisqrt(unsigned t) {
  unsigned s, b;
  for (b = 0, s = t; b++, s >>= 1) {
    ;
  }

  s = 1u << (b >> 1);
  if (b & 1) {
    s += s >> 1;
  }

  do {
    b = t / s;
    s = (s + b) >> 1;
  } while (b < s);

  return s;
}

如果您不喜歡這種高級方法,則代碼可能會緩慢地迭代。 無需迭代到i<n ,而是迭代到i <= n/i

unsigned uisqrt(unsigned n) {
  unsigned i = 0;
  if (n > 0) {
    for (i = 1; i <= n/i; i++) {
      ;
    }
    i--; 
  }
  return i;
}

然后檢查很容易

#include <stdbool.h>

bool check_if_perfect_square(unsigned n) {
  unsigned sr = uisqrt(n);
  return sr*sr == n);
}

然后將此函數應用於正整數的向量

配備了check_if_perfect_square() ,只需遍歷數組即可。

#include <stddef.h>
#include <stdio.h>

void square_root_test_array(unsigned *a, size_t array_length) {
  for (size_t i = 0; i<array_length; i++) {
    if (check_if_perfect_square(a[i])) {
      printf("%u is a perfect square\n",a[i]);
    } else {
      printf("%d is not a perfect square\n",a[i]);
    }
  }
}

樣品使用

int main() {
  printf("\nThe size:\n");
  unsigned n = 0;
  scanf("%u",&n);
  unsigned a[n];

  for(unsigned i=0; i<n; i++) {
    printf("a[%u] = ",i);
    scanf("%d",&a[i]);
  }

  // Now test array
  square_root_test_array(a, n);
  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM