c - 我希望能够向自身添加变量,以便它们与我分配给它们的值相匹配

标签 c variables while-loop

我希望能够给出尽可能多的价格,当我结束循环时,它将写入所有价格的总和,以便我稍后可以将总和转换为瑞典克朗货币。在分配中我应该能够添加新价格,只要它超过 0。

while (price < 0) {
   printf("Give price (finish with <0) :\n");
   scanf("%lf", &price );

   if (price < 0) {
     printf("Sum in foreign currency: %lf\n", sum);
   }
}

这就是我的代码应该如何工作:

Your shopping assistant

1. Set exchange rate in SEK (current rate: 1.00)
2. Read prices in the foreign currency
3. End

Give your choice (1 - 3): 1

Give exchange rate: 9.71

1. Set exchange rate in SEK (current rate: 9.71)
2. Read prices in the foreign currency
3. End

Give your choice (1 - 3): 4

Not a valid choice!!

1. Set exchange rate in SEK (current rate: 9.71)
2. Read prices in the foreign currency
3. End

Give your choice (1 - 3): 2

Give price (finish with <0): 2.75
Give price (finish with <0): 3.50
Give price (finish with <0): -23

Sum in foreign currency: 6.25
Sum in SEK: 60.69

1. Set exchange rate in SEK (current rate: 9.71)
2. Read prices in the foreign currency
3. End

Give your choice (1 - 3): 3

End of program!

最佳答案

  • 循环应在 price 非负数时执行,并且应在循环结束时进行检查。在循环开始时,价格还不知道。

  • price 仅当 scanf 返回 1 时才有效,因此您需要检查这一点。

#include <assert.h>
#include <stdio.h>

double getPriceSum() {
    double sum = 0.0;
    double price;
    do {
        printf("Give price (finish with <0) :\n");
        int num = scanf("%lf", &price);
        if (num != 1)
            price = 0.0; // set a "safe" value for price
        else if (price > 0.0) {
            assert(num == 1); // asserts are like comments that the compiler understands:)
            sum += price;
        }
    } while (price >= 0);

    assert(price < 0); // otherwise the loop wouldn't terminate

    return sum;
}

int main() {
    // ...
    double sum = getPriceSum();
    printf("Sum in foreign currency: %lf\n", sum);
}

在循环内部声明 price 变量会更好,因为外部不需要它,然后我们不需要设置其初始值的体操,这样循环就赢了不要无意中终止:

double getPriceSum() {
    double sum = 0.0;
    for (;;) { // repeat "forever" unless otherwise exited
        double price;
        printf("Give price (finish with <0) :\n");
        int num = scanf("%lf", &price);
        if (num == 1) {
            if (price >= 0.0)
                sum += price;
            else 
                return sum;
        }
    }
}

请注意,带有 \nprintf 会将光标移动到另一行并将输出刷新到屏幕。您可能不希望光标移动(根据示例输出)。相反,删除 \n 并发出显式刷新:

printf("Give price (finish wih <0) : ");
fflush(stdout);

也可以不那么尴尬,接受一个单词而不是数字作为“退出”命令:

double getPriceSum() {
    double sum = 0.0;
    char *line = NULL;
    size_t lineSize = 0;
    for (;;) {
        printf("Give price, or DONE to finish : ");
        fflush(stdout);
        int result = getline(&line, &lineSize, stdin);
        if (result < 0)
            break;
        if (!line || !lineSize)
            continue; // read again
        if (strcmp(line, "DONE") == 0 || strcmp(line, "done") == 0)
            break;
        double price;
        result = sscanf(line, "%lf", &price);
        if (result == 1 && price > 0)
            sum += price;
        else
            fprintf(stderr, "  - Invalid price. Try again.\n");
    }
    return sum;
}

关于c - 我希望能够向自身添加变量,以便它们与我分配给它们的值相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58303919/

相关文章:

javascript - 在 Javascript/React 中从另一个文件调用全局字符串

javascript - HTML 元素作为 While 条件

c - 计算二进制时无限循环

python - 使用管道将命令发送到 python 解释器中

c - 错误计算均值和标准差

powershell - 在 Powershell 中重定向 DLL 输出

javascript - jQuery - 在变量元素内引用伪/其他类

python - 如何填充 TSV 文件中缺失的序列行

c++ - 双 bool 否定运算符

java - JNR 的回调/闭包采用指针参数