打折可以通过多种编程语言实现,以下是几种常见编程语言的打折计算方法:
1. 使用C语言
```c
include
int main() {
int price, discount;
float final_price;
printf("请输入商品原价: ");
scanf("%d", &price);
printf("请输入折扣(1-9): ");
scanf("%d", &discount);
if (discount < 1 || discount > 9) {
printf("折扣输入错误,请输入1-9之间的整数。\n");
return 1;
}
final_price = (float)price * (discount / 10.0);
printf("打折后价格为: %.2f元\n", final_price);
return 0;
}
```
2. 使用Python
```python
def calculate_discounted_price(original_price, discount_rate):
return original_price * discount_rate
original_price = float(input("请输入商品原价: "))
discount_rate = float(input("请输入折扣力度(例如,输入0.9表示九折): "))
discounted_price = calculate_discounted_price(original_price, discount_rate)
print(f"打折后价格为: {discounted_price:.2f}元")
```
3. 使用Java
```java
import java.util.Scanner;
public class DiscountCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入商品原价: ");
double originalPrice = scanner.nextDouble();
System.out.print("请输入折扣力度(例如,输入0.9表示九折): ");
double discountRate = scanner.nextDouble();
if (discountRate < 0.1 || discountRate > 1.0) {
System.out.println("折扣输入错误,请输入0.1到1.0之间的数。");
return;
}
double discountedPrice = originalPrice * discountRate;
System.out.printf("打折后价格为: %.2f元\n", discountedPrice);
}
}
```
4. 使用PHP
```php
<?php
function calculate_discounted_price($original_price, $discount_rate) {
return $original_price * $discount_rate;
}
$original_price = floatval(readline("请输入商品原价: "));
$discount_rate = floatval(readline("请输入折扣力度(例如,输入0.9表示九折): "));
if ($discount_rate < 0.1 || $discount_rate > 1.0) {
echo "折扣输入错误,请输入0.1到1.0之间的数。\n";
exit;
}
$discounted_price = calculate_discounted_price($original_price, $discount_rate);
echo "打折后价格为: " . number_format($discounted_price, 2) . "元\n";
?>
```
5. 使用JavaScript
```javascript
function calculateDiscountedPrice(originalPrice, discountRate) {
return originalPrice * discountRate;
}
const originalPrice = parseFloat(prompt("请输入商品原价:"));
const discountRate = parseFloat(prompt("请输入折扣力度(例如,输入0.9表示九折): "));
if (discountRate < 0.1 || discountRate > 1.0) {
alert("折扣输入错误,请输入0.1到1.0之间的数。");
return;
}
const discountedPrice = calculateDiscountedPrice(originalPrice, discountRate);
alert(`打折后价格为: ${discountedPrice.toFixed(2)}元`);
```
这些示例代码展示了如何在不同编程语言中实现打折计算。你可以根据具体需求选择合适的编程语言和实现方式。