0

我正在尝试执行一个程序,该程序在 && 运算符返回 true 和返回 false 时打印数值。代码如下:-

#include <stdio.h>
main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("Part I\n");
printf("(a%2 == 0) && (b%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
printf("(a%3 == 0) && (b%3 == 0): %d\n",(a%3 == 0) && (b%3 == 0));
printf("(a%5 == 0) && (b%5 == 0): %d\n",(a%5 == 0) && (b%5 == 0));
printf("(a%7 == 0) && (b%7 == 0): %d\n",(a%7 == 0) && (b%7 == 0));
printf("Part II\n");
printf("The AND operator yields: %d\n",(a%2 == 0) && (b%2 == 0));
printf("The AND operator yields: %d\n",(a%3 == 0) && (b%3 == 0));
printf("The AND operator yields: %d\n",(a%5 == 0) && (b%5 == 0));
printf("The AND operator yields: %d\n",(a%7 == 0) && (b%7 == 0));

return 0;
}

输出(连同我的输入)如下: -

210
210
Part I
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
Part II
The AND operator yields: 1
The AND operator yields: 1
The AND operator yields: 1
The AND operator yields: 1

为什么第一部分以这种方式表现?即使我将 && 替换为 || 也会发生这种情况。我正在使用 Borland C++ 编译器 5.5 。请帮忙。

4

3 回答 3

4

因为如果你想实际显示一个%,那么你必须在printf格式字符串中用另一个转义它%。例如

printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
          ^              ^
于 2013-01-12T20:28:51.680 回答
0

我已经用http://codepad.org/对此进行了测试,我认为它使用了 gcc,并且代码运行正常。%但是您可能会尝试在文字%(即)之前添加额外的内容,%%以便编译器知道后面的 % 是实际字符。像这样:

printf("Part I\n");
printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
printf("(a%%3 == 0) && (b%%3 == 0): %d\n",(a%3 == 0) && (b%3 == 0));
printf("(a%%5 == 0) && (b%%5 == 0): %d\n",(a%5 == 0) && (b%5 == 0));
printf("(a%%7 == 0) && (b%%7 == 0): %d\n",(a%7 == 0) && (b%7 == 0));
于 2013-01-12T20:37:45.190 回答
0

您实际上是%在第一部分使用非法转义序列字符进行打印。这就是 printf 产生垃圾值的原因。

printf("(a%2 == 0) && (b%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
              ^ ^
      这是你误会了

它应该像

printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));  

您还可以阅读C 中使用的所有格式说明符

于 2015-05-25T03:49:44.073 回答