简体   繁体   English

在C中以多个数字返回奇/偶数

[英]return odd/even number in C with multiple numbers

I'm trying to write a program that will take two numbers and depending on their values, return both are odd, both are even, or A is odd and B is even, etc. 我正在尝试编写一个程序,该程序将使用两个数字,并根据它们的值返回两个都是奇数,两个都是偶数,或者A是奇数,B是偶数,等等。

I managed to get the program to check one variable but if I add in the second variable I get an output that I don't expect and I can't seem to be able to arrange the code to give the correct output. 我设法使程序检查一个变量,但是如果我添加第二个变量,则会得到我不期望的输出,而且我似乎无法安排代码以提供正确的输出。 I'm guessing that it is a problem with the arrangement of the if/else statements. 我猜想if / else语句的安排有问题。

#include <stdio.h>

int main()
{
    int numA, numB;
    printf("Please enter variables:");
    scanf("%d, %d", &numA, &numB);
    if (numA % 2) {
        printf("Variable A:%d is odd \n",numA);
    }
else{
    printf("Variable A:%d is even \n", numA);
}
if (numB % 2) {
    printf("Variable B:%d is odd \n",numB);
}
else{
    printf("Variable B:%d is even \n", numB);
}
return 0;
}

The output I get is below 我得到的输出如下

Please enter variables:4 5
Variable A:4 is even 
Variable B:32767 is odd 

Why is variable B:32767 not 5? 为什么变量B:32767不是5?

Many thanks for the help as ever. 非常感谢您一如既往的帮助。 If I can sort this out, hopefully I can figure out the rest for myself. 如果我能解决这个问题,希望我能自己解决其余的问题。

Your scanf format expects the numbers to be separated by a comma, 您的scanf格式期望数字用逗号分隔,

scanf("%d, %d", &numA, &numB);

but your input wasn't, so only the first number was converted by scanf and the second was uninitialised. 但是您的输入不是,因此只有第一个数字由scanf转换,而第二个未初始化。

You should always check the return value of scanf and friends to verify that the correct number of conversions was made. 您应该始终检查scanf和friends的返回值,以确认转换次数正确。

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

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