简体   繁体   中英

Function to find odd numbers returns extra value - C Language

I wrote a code in C to find the odd numbers from a given interval of min and max number. The function works well when it is inside the int main() but not well when outside the program as a function.

What's more is that it also prints the incremented number outside the max number given.

This is the code...

#include <stdio.h>
// My Function
int odd_numbers(int x, int y) {
    for (int i = x; i <= y; ++i) {
        if (i % 2 == 1) {
            printf("%d\n",i);
        }
    }
}

// Main Program
int main(void) {
    int min_num, max_num;

    printf("Input your minimum number: ");
    scanf("%d", &min_num);
    printf("Input your maximum number: ");
    scanf("%d", &max_num);

    printf("%d",odd_numbers(min_num,max_num));
}

and this is the output... As you can see, it adds an 11 besides the 9... How can I solve this? I've tried return 0; and it returns the value 0 but i only want to return no number except the odd numbers.

Here is the working code.

Notes

  1. Change the return type of odd_numbers from int to void because you are not returning anything when the function is called.

  2. Only call the function odd_numbers , no need to printf anything because odd_numbers already does the job.

#include <stdio.h>
// My Function
void odd_numbers(int x, int y) {
    for (int i = x; i <= y; i++) {
        if (i % 2 != 0) {
            printf("\n%d",i);
        }
    }
}

// Main Program
int main(void) {
    int min_num, max_num;

    printf("Input your minimum number: ");
    scanf("%d", &min_num);
    printf("Input your maximum number: ");
    scanf("%d", &max_num);

    odd_numbers(min_num,max_num);
}

Here is the modified code.

  1. you have declare function return type int but return nothing. odd_numbers made to void type. no need to return anything

code:

#include <stdio.h>

// My Function
void odd_numbers(int x, int y) 
{
    int i = 0;
    for (int i = x; i <= y; i++) 
    {
        if (i % 2 != 0) 
        {
        printf("%d\n", i);
        }
    }
}

// Main Program
int main(void) {
  int min_num, max_num;

    printf("Input your minimum number: ");
    scanf("%d", &min_num);
    printf("Input your maximum number: ");
    scanf("%d", &max_num);

    odd_numbers(min_num, max_num);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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