所以我是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;
}
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。