[英]So,I made this simple C program to give output,so it is correct for positive and zero integer values but it is coming wrong for negative even and odd
How to get out of this first if else construct because when I input Negative values,because the condition here is checked and then it goes to the last else statement where this just prints zero如何首先摆脱这个 if else 构造,因为当我输入负值时,因为这里的条件被检查,然后它进入最后一个 else 语句,它只打印零
#include<stdio.h>
int main() {
int x;
scanf("%d", &x);
if(x>0)
{
printf("Positive");
{
if(x%2==0)
{
printf("Even");
}
else
{
printf("Odd");
}
}
I want this to be executed when I input negative values,but I'm unable to do so我希望在输入负值时执行此操作,但我无法这样做
if(x<0)
{
printf("Negative");
{
if(x%2==0) {
printf("Even");
}
else {
printf("Odd");
}
}
}
}
else {
printf("Zero");
}
return 0;
}
Just reindent your code you will find strange {
like the one after printf("Positive");
只需重新缩进你的代码,你会发现奇怪的
{
就像printf("Positive");
之后的那个
Juste removing this strange {
and fixing your coding style will be:只是删除这个奇怪的
{
并修复你的编码风格将是:
#include<stdio.h>
int main() {
int x;
scanf("%d", &x);
if ( x > 0 ) {
printf("Positive");
if ( x % 2 == 0 ) {
printf("Even");
} else {
printf("Odd");
}
} else if( x < 0 ) {
printf("Negative");
if( x % 2 == 0 ) {
printf("Even");
} else {
printf("Odd");
}
}
else {
printf("Zero");
}
return 0;
}
easier to read, easier to debug更容易阅读,更容易调试
It seems the problem is an incorrect nesting of compound statements.问题似乎是复合语句的错误嵌套。
I can suggest the following solution.我可以建议以下解决方案。
#include <stdio.h>
int main( void )
{
enum { Negative = -1, Zero = 0, Positive = 1};
printf( "Enter a number: " );
int x = 0;
scanf( "%d", &x );
int sign = ( 0 < x ) - ( x < 0 );
switch (sign)
{
case Negative:
printf( "Negative " );
break;
case Zero:
puts( "Zero" );
break;
case Positive:
printf( "Positive " );
break;
}
if (sign != 0)
{
puts( x % 2 == 0 ? "even." : "odd." );
}
}
The program output might look like程序 output 可能看起来像
Enter a number: 10
Positive even.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.