计算商品打折后金额

这是三个不同的方法,这三个代码优点从低到高越来越明显

include

using namespace std;
int main()
{
double n;
cin >> n;
if (n <= 100)
cout << (float)n << endl;
else if (n >= 100 && n < 500)
cout << (float)(n * 0.8) << endl;
else if (n >= 500 && n < 2000)
cout << (float)(n * 0.7) << endl;
else
cout << (float)(n * 0.6) << endl;

return 0;

}

include

int main()
{
double cost;
cin >> cost;
double price = 0.0;
price = cost >= 5000 ? cost * 0.6 :
cost >= 2000 ? cost * 0.7 :
cost >= 500 ? cost * 0.8 :
cost >= 100 ? cost * 0.9 : cost;
cout << fixed << setprecision(1) << price << endl;

}

int main()
{
double arr1[4] = { 100,500,2000,5000 };
double arr2[4] = { 1,0.8,0.7,0.6 };
double cost;
cin >> cost;
for (int i = 0; i < 4; i++)
{
if (cost > arr1[i] && cost < arr1[i + 1])
cout << cost * arr2[i+1];
}
}

posted @ 2024-10-20 09:33  韦旋  阅读(14)  评论(0)    收藏  举报