这是为什么C程序赋予运行时错误 [英] why is this c program giving runtime error

查看:99
本文介绍了这是为什么C程序赋予运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的计划是采取整数输入,并添加单负数的总和,甚至正数,但我得到运行时错误,任何人都可以找到的错误。

 的#include<&stdio.h中GT;INT主要(无效)
 {INT I,J,M,N,A [M],W;    scanf函数(%d个,&安培; N);
    对于(i = 0; I< N;我++)
    {INT S = 0,D = 0;
        scanf函数(%d个,&安培; M);
        为(J = 0; J<米; J ++)
        {
            scanf函数(%d个,&安培;一个[J]);
            如果((一[J]℃下)及和放大器;!(一个[J]%2 = 0))
             S = S + A [J]。
        否则,如果((一[J]大于0)及及(A [J]%2 == 0))
        D = D + A [J]。
        }
        的printf(%d个S + D);
            }
    返回0;
}


解决方案

在您的code

  A [M]。

是错误的。值 M 被用作初始化。

要解决您的问题,您可以使用动态内存分配的变量为int * A 根据用户输入 M

请注意:


  1. 总是初始化局部变量。

  2. 检查 scanf()的的返回值成功输入。

  3. [请求] C 忽略的空格[大多]。利用它们让你的code以上的人类可读

my program is to take input of integers and add sum of odd negative numbers to even positive numbers but i am getting runtime error,can anyone find mistake.

#include <stdio.h>

int main(void)
 {

int i,j,m,n,a[m],w;

    scanf("%d",&n);
    for(i=0;i<n;i++)
    {   int s=0,d=0;
        scanf("%d",&m);
        for(j=0;j<m;j++)
        {
            scanf("%d",&a[j]);  
            if((a[j]<0)&&(a[j]%2!=0))
             s=s+a[j];
        else if((a[j]>0)&&(a[j]%2==0))
        d=d+a[j];
        }
        printf("%d",s+d);
            }
    return 0;
}

解决方案

in your code

a[m]

is erroneous. value of m is used as uninitialized.

To solve your issue, you can use dynamic memory allocation for a variable int * a based on the user input of m.

Note:

  1. Always initialize your local variables.
  2. Check the return value of scanf() for successful input.
  3. [A request] C ignores white-spaces [mostly]. Use them to make your code more human-readable.

这篇关于这是为什么C程序赋予运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆