课后作业s1e14的动手题第二个的进阶题
本帖最后由 如果孤独感 于 2021-10-22 13:07 编辑输出时出现只能输出两行就退出的情况;
在while的最后加getchar();也得不到改善;
这是什么情况?
int main()
{
float ch, sum = 0, d, number, x = 0;
bool dian, isOdd = 1;
while (isOdd)
{
printf("请输入合法的数字:");
for (d = 1, dian = 0, number = 0; (ch = getchar()) != '\n';)
{
if (dian)
{
d /= 10;//实现小数点后的分数
}
if (ch == '.')
{
dian = 1;
}
if (ch >= '0' && ch <= '9')
{
number += 1;
sum += (ch - '0')*d; //数字和
}
else if (number > 0 && !(ch >= '0' && ch <= '9') && ch != '.')//让程序能以任意字符为数字间隔
{
dian = 0;
number = 0;
}
else
{
isOdd = 0;//退出while循环
}
}
}
printf("结果是:%.2f\n", sum);
你这代码是实现什么功能的?
#include <stdio.h>
#include <math.h>
int main()
{
float ch, sum = 0, d, number, x = 0;
bool dian, isOdd = 1;
while (isOdd)
{
printf("请输入合法的数字:");
for (d = 1, dian = 0, number = 0; (ch = getchar() )!= '\n';)
{
if (dian)
{
d /= 10;//实现小数点后的分数
}
if (ch == '.')
{
dian = 1;
}
if (ch >= '0' && ch <= '9')
{
number += 1;
sum += (ch - '0')*d; //数字和
}
else if (number > 0 && !(ch >= '0' && ch <= '9') && ch != '.')//让程序能以任意字符为数字间隔
{
dian = 0;
number = 0;
}
else
{
isOdd = 0;//退出while循环
}
}
}
printf("结果是:%.2f\n", sum);
return 0;
} 有点不明白你的问题,改了一下代码
#include <stdio.h>
#include <stdbool.h>
int main()
{
float ch, sum = 0, d, number;
bool dian, isOdd = 1;
while (isOdd)
{
printf("请输入合法的数字:");
for (d = 1, dian = 0, number = 0; (ch = getchar()) != '\n';)
{
if (dian)
{
d /= 10;//实现小数点后的分数
}
if (ch == '.')
{
dian = 1;
}
if (ch >= '0' && ch <= '9')
{
number += 1;
sum += (ch - '0')*d; //数字和
}
else if (number > 0 && !(ch >= '0' && ch <= '9') && ch != '.')//让程序能以任意字符为数字间隔
{
dian = 0;
number = 0;
}
else
{
isOdd = 0;//退出while循环
}
}
}
printf("结果是:%.2f\n", sum);
return 0;
} 大马强 发表于 2021-10-22 12:55
你这代码是实现什么功能的?
课后作业s1e14期的第二个动手题的进阶
页:
[1]