无法运行基本的C程序

时间:2015-01-10 20:43:34

标签: c

我正在尝试运行一个简单的代码,它从用户那里获取两个数字并打印它们的总和 那是:

#include <stdio.h>
#include <conio.h>

void main() {
    int n1 = 0, n2 = 0, sum = 0;
    printf("Insert two numbers:\n");
    scanf("%d %d", n1, n2);
    sum = n1 + n2;
    printf("The sum of %d and %d is - %d\n", n1, n2, sum);
    printf("%d + %d = %d", n1, n2, sum);
    getch();
}

我正在尝试运行它,当我执行第一个打印命令时,当我按Enter键进行扫描时崩溃,我正在使用code :: blocks 13.12来编译和运行 谢谢! :)

2 个答案:

答案 0 :(得分:4)

您的程序崩溃是因为您正在将数字扫描到错误的内存地址。改变

scanf("%d %d", n1, n2);  

scanf("%d %d", &n1, &n2);

答案 1 :(得分:0)

您的程序无法运行,因为scanfint"%d"指针设置n1,因此请传递n2和{{1}的地址而不是n1n2

#include <stdio.h>
#include <conio.h>

void main() {
    int n1 = 0, n2 = 0, sum = 0;
    printf("Insert two numbers:\n");
    scanf("%d %d", &n1, &n2);
    /*             ^    ^ address of operater, take the addreess of n2 and pass it */
    /*             | address of operater, take the addreess of n1 and pass it */
    sum = n1 + n2;
    printf("The sum of %d and %d is - %d\n", n1, n2, sum);
    printf("%d + %d = %d", n1, n2, sum);
    getch();
}

但不仅如此,您应该检查实际上读取的数字,否则您的程序将调用未定义的行为,以确保您成功读取整数,您应该检查它返回的scanf的返回值匹配的参数数量,所以

#include <stdio.h>
#include <conio.h>

void main() {
    int n1 = 0, n2 = 0, sum = 0;
    printf("Insert two numbers:\n");

    /* if it equals two it succeeded, since we requested two integers */
    if (scanf("%d %d", &n1, &n2) == 2)
    {
        sum = n1 + n2;
        printf("The sum of %d and %d is - %d\n", n1, n2, sum);
        printf("%d + %d = %d", n1, n2, sum);
    }
    else
    {
        printf("error reading 2 integers\n");
        return 1; /* non zero means error */
    }
    getch();
    /* return success from main() */
    return 0;
}