gpt4 book ai didi

c - 使用 Switch Case 缩短重复代码

转载 作者:行者123 更新时间:2023-11-30 18:33:40 24 4
gpt4 key购买 nike

有没有办法把这段代码转换成5行,看起来很重复。

我想使用开关盒。另外,我希望将其保持在初学者水平。

void SortProductList(Product *productList, int size, char sortOption){
Product temp;

for (int i=0; i<size-1; i++)
{
for (int j=i+1; j<size; j++)
{
if (sortOption == 'p') //sorting by price
{
if (productList[j].productPrice<productList[i].productPrice) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
if (sortOption == 'w') //sorting by weight
{
if (productList[j].productWeight<productList[i].productWeight) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
if (sortOption == 'n') //sorting by weight
{
if (strcmp(productList[j].productName,productList[i].productName)<0) //second is bigger than first
{
temp = productList[i];
productList[i] = productList[j];
productList[j]=temp;
}
}
}
}
}

最佳答案

Switch 语句似乎并没有让你比现在更进一步,试试这个:

for (int i = 0; i < size - 1; i++){
for (int j = i + 1; j < size; j++){
if ((sortOption == 'p' && productList[j].productPrice < productList[i].productPrice) ||
(sortOption == 'w' && productList[j].productWeight < productList[i].productWeight) ||
(sortOption == 'n' && (strcmp(productList[j].productName, productList[i].productName) < 0))){
temp = productList[i];
productList[i] = productList[j];
productList[j] = temp;
}
}
}

关于c - 使用 Switch Case 缩短重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55350344/

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