这串代码哪里写错了,为什么我输入一个整数它直接就结束了

img


这串代码哪里写错了,为什么我输入一个整数它直接就结束了
用的是vs2022编译器

第一个scanf_s不对,注意你的引号,不能包括后面
status = scanf_s("%ld", &num);

【以下回答由 GPT 生成】

错误所在是在使用scanf_s函数读取整数值时的格式字符串。在代码中,格式字符串"%ld"用于读取long类型的整数值,但是在scanf_s函数中,需要将格式字符串中的%符号转义为%%,否则会导致程序直接结束。

正确的格式字符串应该是"%%ld",表示读取一个long类型的整数值。

修改后的代码如下:

#include<stdio.h>
#include<math.h>

int main(void) {
    printf("What is the value of pi?\n");

    double answer = 3.14159;
    double response;
    scanf_s("%lf", &response);

    while (fabs(response - answer) > 0.0001) {
        printf("Try again!\n");
        scanf_s("%lf", &response);
    }

    printf("Close enough!\n");

    long num;
    long sum = 0;
    int status;

    printf("Please enter an integer to be summed (enter 'q' to quit):");
    status = scanf_s("%%ld", &num);

    while (status == 1) {
        sum += num;
        printf("Please enter next integer (enter 'q' to quit):");
        status = scanf_s("%%ld", &num);
    }

    printf("The sum of those integers is %ld.\n", sum);
    return 0;
}


【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^