所以我是C语言的完整入门者,并且正在为该语言而苦苦挣扎。我需要编写一个程序,如果他们输入一个负数,直到用户产生一个正数,它会再次提示用户输入数字。到目前为止,我的显示如下,没有错误消息显示,但是当我输入负浮点值时,它不会再次提示我,而是显示数字。有任何想法吗?
#include <cs50.h>
#include <stdio.h>
#include <math.h>
float get_positive_float(string prompt);
int main(void)
{
float f = get_float("Cash: ");
printf("%f\n", f);
}
float get_positive_float(string prompt)
{
float n;
do {
n = get_float("%s", prompt);
} while (n < 0);
return n;
}
答案 0 :(得分:0)
float get_positive_float(char const *prompt)
{
float result;
while (prompt && printf(prompt), scanf(" %f", &result) != 1 || result < 0.f) {
fputs("Please only enter positive values!\n\n", stderr);
for (int ch; (ch = getchar()) != '\n' && ch != EOF;); // clear the rest of the line
}
return result;
}
使用<cs50.h>
中的东西的版本可能看起来像这样:
float get_positive_float(string prompt)
{
float result;
while ((result = get_float(prompt)), result < 0.f) {
fputs("Please only enter positive values!\n\n", stderr);
}
return result;
}
问题是,浮点数不适用于金额。使用整数类型并以美分计算。对于输出除以100。