我们可以扫描一个数组吗?
Can we scanf an array?
我想输入一个整数数组,然后从输入的数字中打印出偶数..
example is if I input 2466688992,
it will output 24666882;
我的代码如下:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
结果变成垃圾:2468000075416640419940000004225568000
这是打印整数偶数的函数:
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
您应该将数组扫描为字符串(除非您想强加数组中的项目数),然后解析字符串以存储不同的数字:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
这会将所有数字存储在大小为 j
的数组 a
中。
编辑:如果您谈论的是数字,那么它更容易:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);
我想输入一个整数数组,然后从输入的数字中打印出偶数..
example is if I input 2466688992,
it will output 24666882;
我的代码如下:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
结果变成垃圾:2468000075416640419940000004225568000
这是打印整数偶数的函数:
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
您应该将数组扫描为字符串(除非您想强加数组中的项目数),然后解析字符串以存储不同的数字:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
这会将所有数字存储在大小为 j
的数组 a
中。
编辑:如果您谈论的是数字,那么它更容易:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);