因此,当我输入正数或正数和负数的输入时,代码可以正常工作,但是仅输入负数会导致浮点错误,我知道除以零会导致这种情况,但是我会根据输入数进行潜水
#include <stdio.h>
int main()
{
int integer, pos, neg;
int poscounter, negcounter;
integer = 0;
pos = 0;
neg = 0;
poscounter = 0;
negcounter = 0;
do {
printf("Please enter an integer:");
scanf("%d", &integer);
if (integer > 0) {
pos += integer;
poscounter++;
}
else
neg += integer;
negcounter++;
} while (integer != 0);
printf("Positive average: = %d", pos / poscounter);
printf("Negative average: = %d", neg / negcounter);
}
因此,输入-3 -2 -1 0的输出应为 “负平均值:-2”
答案 0 :(得分:1)
#include <stdio.h>
int main()
{
int integer, pos, neg;
int poscounter, negcounter;
integer = 0;
pos = 0;
neg = 0;
poscounter = 0;
negcounter = 0;
do {
printf("Please enter an integer:");
scanf("%d", &integer);
if (integer > 0) {
pos += integer;
poscounter++;
}
else if(integer < 0) // Added else if for the logic as it was considering 0 as negative
{
neg += integer;
negcounter++;
}
} while (integer != 0);
printf("posc = %d\n", poscounter); // Printed for confirmation
printf("negc = %d\n", negcounter); // Printed for confirmation
/* Added these two ifs so that it can check any of the counters is not zero and it will not give (core dumped) */
if(poscounter)
printf("Positive average: = %d\n", pos / poscounter);
if(negcounter)
printf("Negative average: = %d\n", neg / negcounter);
return 0; // Adding this is a good practice
}
嘿,他们的逻辑有点问题,因为当未遇到正/负时,它会将表达式除以0。此外,它还将0视为负整数。 请发表评论可能会有所帮助
答案 1 :(得分:1)
这将导致输入-3,-2,-1,0崩溃,因为如果(integer> 0)始终为false,则poscounter不会在任何时候递增,因此poscounter在while循环后将为零。
printf(“正平均值:=%d”,正/负);由于零操作的决定,将使程序崩溃。
最好先进行分母if检查,并确保在使用devide操作之前将其设为零:
if (0 != poscounter)
printf("Positive average: = %d", pos / poscounter);
这将确保仅在poscounter为非零值的有效情况下才执行printf。
答案 2 :(得分:1)
if (integer > 0)
从未执行,因此poscounter
从未递增,因此最后的除法pos / poscounter
无法正常工作。