简体   繁体   English

不确定为什么我尝试关闭程序时提示提示错误?

[英]Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>

int add_even(int);
int add_odd(int);

int main() {
    int num, result_odd, result_even, even_count, odd_count;
    char name;

    printf("What is your name?\n");
    scanf("%s", &name);

    while (num != 0) {
        printf("Enter a number:\n");
        scanf("%d", &num);

        if (num % 2 == 1) {
            printf ("odd\n");
            odd_count++;
        } else
        if (num == 0) {
            printf("%s, the numbers you have entered are broken down as follows:\n",
                  name);
            result_even = add_even(num);
            printf("You entered %d even numbers with a total value of %d\n",
                   even_count, result_even);
            result_odd = add_odd(num);
            printf("You entered %d odd numbers with a total value of %d\n",
                   odd_count, result_odd);
        } else {
            printf("even\n");
            even_count++;
        }
    }
    return 0;
} 

int add_even(int num) {
    static int sum = 0;

    if (num % 2 != 0) {
        return 0;
    }

    sum += add_even(num);
    return sum;
}

int add_odd(int num) {
    static int sum = 0;

    if (num % 2 == 0) {
        return 0;
    }
    sum += add_odd(num);
    return sum;
}

Can anyone give me some insight as to what I did wrong exactly? 谁能给我一些关于我到底做错了什么的见解?

The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. 代码的重点是从用户那里获取输入,直到他们决定通过输入0停止输入为止。将偶数与奇数分开。 Tell them how many even/odd they put and the total of all the even/odd numbers. 告诉他们他们放了多少个偶/奇数以及所有偶/奇数的总数。

I understand how to separate the evens from the odds. 我了解如何将赔率与赔率区分开。 I think my issue is with my function. 我认为我的问题与我的职能有关。

There are multiple problems in your code: 您的代码中存在多个问题:

  • scanf() causes undefined behavior when trying to store a string into a single character. 尝试将字符串存储为单个字符时, scanf()导致未定义的行为。 Pass an array and specify a maximum length. 传递数组并指定最大长度。

  • you should check the return value of scanf() : if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. 您应该检查scanf()的返回值:如果scanf()未能根据规范转换输入,则该值未修改,因此未初始化,并且随后出现未定义的行为。 In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set. 在您的情况下,如果在提示符下键入2个或更多单词,则scanf("%d",...)失败,因为未输入数字,未从stdin读取其他字符,并且未设置num

  • num is uninitialized in the first while (num != 0) , causing undefined behavior. num在第一个while (num != 0)未初始化while (num != 0) ,从而导致未定义的行为。

  • functions add_even() and add_odd() are only called for num == 0 , never summing anything. 函数add_even()add_odd()仅在num == 0调用,从不求和。

  • functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. 函数add_even()add_odd()应该始终返回总和并添加参数num的值(如果它具有正确的奇偶校验)。 They currently cause undefined behavior by calling themselves recursively indefinitely. 当前,它们通过无限期地递归调用自身来导致未定义的行为。
  • odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior. odd_counteven_count计数未初始化,因此计数将不确定,并且读取它们将调用未定义的行为。

In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. 尽管上面提到了未定义行为的所有来源,但如果您键入的名称名称超过一个单词,则程序不断提示而不期望答案的原因。 Only a single word is converted for %s , leaving the rest as input for numbers, which repeatedly fails in the loop. %s只转换一个单词,其余的作为数字的输入,这在循环中反复失败。 These failures go unnoticed as you do not verify the return value of scanf() . 由于您不验证scanf()的返回值,因此这些故障不会引起注意。

Here is a corrected version: 这是更正的版本:

#include <stdio.h>
#include <stdlib.h>

int add_even(int);
int add_odd(int);

int main(void) {
    int num, result_odd, result_even, even_count = 0, odd_count = 0;
    char name[100];

    printf("What is your name? ");
    if (scanf("%99[^\n]", name) != 1)
        return 1;

    for (;;) {
        printf("Enter a number: ");
        if (scanf("%d", &num) != 1 || num == 0)
            break;

        if (num % 2 == 1) {
            printf("odd\n");
            odd_count++;
            add_odd(num);
        } else {
            printf("even\n");
            even_count++;
            add_even(num);
        }
        printf("%s, the numbers you have entered are broken down as follows:\n", name);
        result_even = add_even(0);
        printf("You entered %d even numbers with a total value of %d\n",
               even_count, result_even);
        result_odd = add_odd(0);
        printf("You entered %d odd numbers with a total value of %d\n",
               odd_count, result_odd);
    }
    return 0;
} 

int add_even(int num) {
    static int sum = 0;

    if (num % 2 == 0) {
        sum += num;
    }
    return sum;
}

int add_odd(int num) {
    static int sum = 0;

    if (num % 2 != 0) {
        sum += num;
    }
    return sum;
}

You declared: 您声明:

char name;                       // One single letter, such as 'A', or 'M'

printf("What is your name?\n");  // Please enter a whole bunch of letters!
scanf("%s", &name);              // Not enough space to store the response!

What you really want is more like 您真正想要的是

char name[31];                   // Up to 30 letters, and an End-of-String marker

printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name);              // name is the location to put all those letters
                                // (but not more than 30!)

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

相关问题 当我尝试运行程序时,为什么我的程序总是崩溃? - How come my program keeps crashing when I try to run it? 不知道为什么我的 function 不断返回错误? - Not sure why my function keeps returning an error? 为什么当我尝试初始化我的指针时我的程序会崩溃? - Why is my program crashing when I try to initialize my pointer? 尝试打印char指针时,为什么我的程序崩溃 - Why is my program crashing when I try to print a char pointer 我的程序无限循环,我老实说不清楚为什么 - My program is looping infinitely, and I'm honestly not sure why 我的 c 程序一直崩溃,我不知道为什么 - My c program keeps crashing and I do not know why 当我尝试重新分配()结构指针数组时,为什么我的 C 程序会崩溃? - Why does my C program crash when I try to realloc() a pointer array of structs? 我的程序有 AddressSanitizer 错误,但我不知道如何阅读 - My program has AddressSanitizer error but I'm not sure how to read it 当我尝试以相反的顺序打印字符串时,为什么我的C程序会打印新的空白行? - Why does my C program print new blank lines when I try to print a string in the reverse order? 当我尝试从单链表中删除节点时,为什么我的 C 程序崩溃 - Why does my C Program crash when I try to delete a node out of a singe linked list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM