我希望能够给出任意数量的价格,当我结束循环时,它将写入所有价格的总和,因此以后我可以将总和转换为SEK货币。在分配中,只要价格超过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;
}
}
}
请注意,将
printf
与\n
一起将光标移至另一行并将输出刷新到屏幕。您可能不希望光标移动(根据示例输出)。相反,请删除\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/