gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:12:35 24 4
gpt4 key购买 nike

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

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