gpt4 book ai didi

c - 为什么此代码打印大值而不是我期望的总数?

转载 作者:行者123 更新时间:2023-11-30 19:06:54 25 4
gpt4 key购买 nike

我正在尝试获取 5 个整数输出并显示奇数计数、偶数计数、奇数总计和偶数总计。这段代码给了我更大的总值(value)。有什么问题吗?

#include <stdio.h>

int main(){
int n,count,oc,ec;
float ot,et,answer;

for(count=0;count<=5;count++){
printf("enter a odd or even number :");
scanf("%d",&n);
}
answer=n%2;
if (answer>0){
oc=oc+1;
ot=n+ot;
}

else {
ec=ec+1;
et=n+et;
}
printf("odd counter is %f",oc);
printf("odd counter is %f",ot);
printf("even counter is %f",ec);
printf("even counter is %f",et);
}

最佳答案

将累加器更改为整数并初始化它们:

int oc, ot, ec, et;
oc = ot = ec = et = 0;

按如下方式移动右大括号:

for(count=0;count<=5;count++){
printf("enter a odd or even number :");
scanf("%d",&n);

answer=n%2;
if (answer>0){
oc=oc+1;
ot=n+ot;
}
else {
ec=ec+1;
et=n+et;
}
}

并将 printf 更改为使用 %d 而不是 %f

printf("odd counter is %d",oc);
printf("odd counter is %d",ot);
printf("even counter is %d",ec);
printf("even counter is %d",et);

关于c - 为什么此代码打印大值而不是我期望的总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com