这些是代码的一些变体,所有变体的输出都是相同的。我尝试过使用指针,并通过定义函数 caseInsensitiveComparision 以及逻辑中的一些细微更改,在由所有更改组合组成的所有变体中,都会产生相同的输出 -
输入选择数量(最多 5 个):3 输入选择 1:idli idli 价格:Rs15/- 输入选择2:茶 茶价:Rs15/- 输入选择 3:设置剂量 在菜单中找不到选择集。 包括 GST 在内的应付账单总额为:Rs30/-
#include <stdio.h>
#include <string.h>
const char items[5][20] = {"TEA", "COFFEE", "IDLI", "SET DOSA", "MASALA DOSA"};
int prices[5] = {15, 20, 15, 30, 40}; // Predefined prices
int findItemIndex(const char *selection) {
for (int i = 0; i < 5; i++) {
if (strcasecmp(selection, items[i]) == 0) {
return i;
}
}
return -1; // Return -1 if not found
}
int main() {
char selections[5][20]; // User inputs for selections
int numSelections, totalBill = 0;
printf("Enter the number of selections (up to 5): ");
scanf("%d", &numSelections);
for (int i = 0; i < numSelections; i++) {
printf("Enter selection %d: ", i + 1);
scanf("%19s", selections[i]);
int index = findItemIndex(selections[i]);
if (index != -1) {
printf("Price for %s: Rs%d/-\n", selections[i], prices[index]);
totalBill += prices[index];
} else {
printf("Selection %s not found in the menu.\n", selections[i]);
}
}
if (totalBill == 0) {
printf("No valid selections found.\n");
} else {
printf("The total bill payable including GST is: Rs%d/-\n", totalBill);
}
return 0;
}
这是另一种变体:
#include <stdio.h>
int caseInsensitiveCompare(const char str1[], const char str2[]) {
int i = 0;
while (str1[i] && str2[i]) {
if (tolower((unsigned char)str1[i]) != tolower((unsigned char)str2[i])) {
return 0; // Not equal
}
i++;
}
return (str1[i] == '\0' && str2[i] == '\0');
}
const char items[5][20] = {"TEA", "COFFEE", "IDLI", "SET DOSA", "MASALA DOSA"};
int prices[5] = {15, 20, 15, 30, 40}; // Predefined prices
int findItemIndex(const char selection[]) {
for (int i = 0; i < 5; i++) {
if (caseInsensitiveCompare(selection, items[i])) {
return i;
}
}
return -1; // Return -1 if not found
}
int main() {
char selections[5][20]; // User inputs for selections
int numSelections, totalBill = 0;
printf("Enter the number of selections (up to 5): ");
scanf("%d", &numSelections);
for (int i = 0; i < numSelections; i++) {
printf("Enter selection %d: ", i + 1);
scanf("%19s", selections[i]);
int index = findItemIndex(selections[i]);
if (index != -1) {
printf("Price for %s: Rs%d/-\n", items[index], prices[index]);
totalBill += prices[index];
} else {
printf("Selection %s not found in the menu.\n", selections[i]);
}
}
if (totalBill == 0) {
printf("No valid selections found.\n");
} else {
totalBill += totalBill * 0.18;
printf("The total bill payable including GST is: Rs%d/-\n", totalBill);
}
return 0;
}
我注意到您的其中一件商品有一个空格:
"MASALA DOSA"
。但是您将 %19s
与 scanf
一起使用。这将在第一个空格处停止读取,这意味着用户输入 MASALA DOSA
会将 MASALA
读入变量中。这显然不会匹配数组中的任何值。
要读取 19 个或更少的字符直至换行,请使用
%19[^\n]
作为格式说明符。