简体   繁体   English

为什么这段代码会给出运行时错误?

[英]Why is this code giving runtime error?

There will be multiple integers in the input.输入中会有多个整数。 You have to write a computer program to read each integer and print Even if the integer is divisible by 2, else print Odd.您必须编写一个计算机程序来读取每个整数并打印即使该整数可以被 2 整除,否则打印 Odd。 To help further, the number of integers (T) to read will be the first input to the computer program.为了进一步提供帮助,要读取的整数 (T) 数将是计算机程序的第一个输入。

Input Format: First line of input contains count of integers: T. T>=1 After that, each line contains the integer N.输入格式:输入的第一行包含整数个数:T。T>=1 之后,每行包含整数N。

Sample Input:样本输入:

2 4 5 2 4 5

Sample Output:示例输出:

Even Odd偶数

#include <stdio.h>

int main()
{   
    int i,T,a[10];/*Assuming Number of integers would be less than 10*/
    printf("Enter the Number of integers\n");
    scanf("%d",&T);
    for(i=0;i<T;i++)
    {
        scanf("%d",a[i]);
        printf("\n");
    }
    for(i=0;i<T;i++)
    {
        if(a[i]%2==0)
            printf("Even\n");
        else
            printf("Odd\n");
    }

    return 0;
}

You have scanf("%d",a[i]);你有scanf("%d",a[i]); . . Scanf is looking for a pointer to an integer, and you're passing an integer (which is likely to be 0 since you haven't assigned anything; note also that zero is generally equal to NULL). Scanf 正在寻找一个指向整数的指针,并且您正在传递一个整数(由于您尚未分配任何内容,因此很可能为 0;另请注意,零通常等于 NULL)。 You want scanf("%d",&a[i]);你想要scanf("%d",&a[i]); . . Also note that your compiler should be giving you a warning about this... if using gcc, you should get in the habit of always compiling code with -Wall还要注意,你的编译器应该给你一个警告……如果使用 gcc,你应该养成总是用-Wall编译代码的习惯

Thanks everyone.谢谢大家。 I found out the error and used dynamic memory allocation for the program.我发现了错误并为程序使用了动态内存分配。 This was the program I used.这是我使用的程序。 If somebody could help me cut down the code to few lines then please help.如果有人可以帮助我将代码减少到几行,那么请帮忙。

#include<stdio.h>
int main()
{
    int i,*ptr,t;
    printf("Enter the count:");
    scanf("%d",&t);
    ptr=(int*)malloc(t*sizeof(int));
    if(ptr==NULL)
    {
        printf("Memory not allocated\n");
        exit(0);
    }
    if(t>=1)
    {
        for(i=0;i<t;++i)
        {
            printf("Enter Data:");
            scanf("%d",ptr+i);
        }
        for(i=0;i<t;i++)
        {
            if((*(ptr+i))%2==0)
                printf("%d is Even\n",*(ptr+i));
            else
                printf("%d is Odd\n",*(ptr+i));
        }
    }   
    return 0;   

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM