找出c中数组中每个数字的第一个数字是否为奇数



基本上,我的c程序需要做的是找出一个数字的第一个数字是否为奇数,并对12个元素的数组中的每个元素都这样做。此外,我还需要使程序以找出单个数字的第一个元素是否为奇数的方式编写,需要在main()之外的特殊函数中编写。这个程序只在main()中很容易编写,但据我所知,如果你想在main()之外对数组做一些事情,你需要对数组使用指针,我不太擅长这个。所以我想你们能帮我个大忙。这是我目前所做的:

#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’

所以就像我说的,任何帮助都会有好处。还要记住,我现在是大学第一学期的第一年,我们还不能真正使用<studio之外的任何东西。或&>来编写代码。

不需要指针,除非你想修改传递的数组。

一些问题:

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

上面的代码在一个无限循环中运行,之后再运行一次p[i] /= 10;

大多数C程序员都有缺少;的问题。你有相反的问题:一个;,它不应该在哪里。

简单地说,侵入的;告诉编译器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元素

如果我想将整个数组传递给我的函数,我将这样写代码:

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)

相关内容

最新更新