影像中的輸出是我看到的詳細資訊:運行它后,它在陣列中給了我零個素數。程式型別:它是一個采用二維陣列 [nxm] 然后計算二維陣列中有多少素數的程式。
int isprime(int n)
{
int k;
if (n <= 1)
return 0;
for (k = 2; k <= (n / 2); k ){
if (n % k == 0)
return 0;
}
return 1;
}
}
int primecount(int x, int y, int a[x][y]){
int r, c, count = 0;
for(r = 0; r < x; r ) {
for(c = 0; c < y; c ) {
if(isprime(a[r][c]))
{
count ;
}
}
}
return count;
}
int main()
{
int n, m, i, j, z;
printf("Enter the Number of Rows: ");
scanf("%d", &n);
printf("\n");
printf("Enter the Number of Columns: ");
scanf("%d", &m);
printf("\n");
int a[n][m];
printf("Enter the elements of the array: \n");
for(i = 0; i < n; i )
{
for(j = 0; j < m; j )
scanf("%d", &a[i][j]);
}
z = primecount(n, m, a[n][m]);
printf("\n");
printf("The Number of Prime Numbers in the array is: %d", z);
printf("\n");
return 0;
}
uj5u.com熱心網友回復:
對于初學者而不是這個電話
z = primecount(n, m, a[n][m]);
你需要寫
z = primecount(n, m, a);
在這個函式isprime 的呼叫中,就像上面顯示的呼叫一樣
if(isprime(r, c, a[r][c]))
運算式a[r][c]是一個型別為 的標量物件int。然而,該函式isprime需要一個二維陣列,而不是一個型別為 的標量物件int。
int isprime(int p, int q, int a[p][q])
^^^^^^^^^^^
只需將函式宣告為
int isprime( int x );
并相應地改變其定義。
該函式將被呼叫
if( isprime( a[r][c] ) )
注意函式的邏輯isprime有誤。對于等于1并且0雖然這些值不是素數的值,它回傳邏輯真。
您還需要處理包含型別為 的元素的陣列unsigned int。否則,用戶可以輸入負值。
這是您更新的程式。
#include <stdio.h>
int isprime(int n)
{
int k;
if (n <= 1)
return 0;
for (k = 2; k <= (n / 2); k )
{
if (n % k == 0)
return 0;
}
return 1;
}
int primecount(int x, int y, int a[x][y]) //function to count prime numbers
{
int r, c, count = 0;
for(r = 0; r < x; r )
{
for(c = 0; c < y; c )
{
if(isprime(a[r][c]))
{
count ;
}
}
}
return count;
}
int main()
{
int n, m, i, j, z;
printf("Enter the Number of Rows: ");
scanf("%d", &n);
printf("\n");
printf("Enter the Number of Columns: ");
scanf("%d", &m);
printf("\n");
int a[n][m];
printf("Enter the elements of the array: \n");
for(i = 0; i < n; i )
{
for(j = 0; j < m; j )
scanf("%d", &a[i][j]);
}
z = primecount(n, m, a);
printf("\n");
printf("The Number of Prime Numbers in the array is: %d", z);
printf("\n");
return 0;
}
它的輸出可能看起來像
Enter the Number of Rows: 2
Enter the Number of Columns: 2
Enter the elements of the array: 1 2 3 4
The Number of Prime Numbers in the array is: 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367261.html
上一篇:如何在c編程中忽略空格?
