簡體   English   中英

在 C 中找出數組中每個數字的第一個數字是否為奇數

[英]Finding out if the first digit of every number in an array is odd in C

所以基本上我的 c 程序需要做的是找出一個數字的第一個數字是否是奇數,並且對 12 元素數組的每個元素都這樣做。 此外,我需要以找出單個數字的第一個元素是否為奇數的方式編寫程序,需要將其寫入 main() 之外的特殊 function 中。 這個程序真的很容易只在 main() 中制作,但據我所知,如果你想在 main() 之外對它做一些事情,你需要對數組使用指針,而我並不擅長那個 tbh。 所以我猜任何幫助都會幫我大忙。 這是我到目前為止所做的:

#include <stdio.h>
int function(int p[], int n)
{
    int i;
    int x;

    for (i = 0; i < n; i++)
    {
        while (p[i] >= 10)
            ;
        {

            p[i] /= 10;
        }

        if (p[i] % 2 != 0)
        {
            x++;
        }
    }
    return x;
}
int main()
{
    int n = 12;
    int array[n];
    int i;

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

    int r;

    r = function(array[n], n);

    printf("%d", r);

    return 0;
}

這就是我明顯的錯誤:

 main.c:31:22: warning: passing argument 1 of 'function' makes pointer from integer without a cast [-Wint-conversion] main.c:3:9: note: expected 'int *' but argument is of type 'int'

所以是的,正如我所說,任何幫助都會有好處。 還要記住,我在大學第一學期的第一年,我們不能真正使用 <stdio.h> 或 <stdlib.h> 之外的任何東西來編寫我們的代碼。

不需要指針,除非您想修改傳遞的數組。


一些問題:

while(p[i] >= 10);{
    p[i] /= 10;
}

上面的代碼在無限循環中運行,之后運行p[i] /= 10; 一次。

大多數 C 程序員都有缺失的問題; . 你有相反的問題: A ; 它不應該在哪里。

簡單地說,就是闖入; 告訴編譯器 while 循環不運行任何代碼,因此編譯器實際上認為您的代碼意味着:

while(p[i] >= 10) {
    // Do nothing
}

p[i] /= 10;


int r;

r = function(array[n], n);

printf("%d", r);

那個 r 變量是沒有意義的。 除非您不想直接從function傳遞返回值

如果n的值為 12,則array[n]array的第 12 個元素。 不存在,因為array只有元素 0-11

如果我想將整個數組傳遞給我的 function,這就是我編寫代碼的方式:

printf("%d", function(array, n));

這是您想要的代碼的工作版本

#include <stdio.h>

int count_odd_fdigits();

int main() {
    const int ARRAY_SIZE = 12;

    int array[ARRAY_SIZE];
    int i;

    for (i=0; i < ARRAY_SIZE; i++) {
        scanf("%d", &array[i]);
    }
    
    printf("Numbers with an odd first digit: %d", count_odd_fdigits(array, ARRAY_SIZE));

    return(0);
}

int count_odd_fdigits(int numbers[], int limit) {
    int i;
    int count = 0;

    for (i=0; i < limit; ++i) {
        while (numbers[i]/10 > 0)
            numbers[i] /= 10;

        if (numbers[i] % 2 != 0)
            ++count;
    }

    return(count);
}

(在線運行: https://onlinegdb.com/yEPr_mYgna

暫無
暫無

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

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