目录1
程序员如何写好代码
目录2
优秀代码案例
写好代码对程序员来说不仅是技术能力的体现,更是思维和习惯的综合。以下是一些编写高质量代码的核心要点:
totalAmount
而不是 a
。def calculate_total_price(prices, tax_rate):
"""
计算总价格,包括税费
:param prices: 商品价格列表
:param tax_rate: 税率
:return: 包含税的总价格
"""
subtotal = sum(prices)
tax = subtotal * tax_rate
total = subtotal + tax
return total
# 示例使用
prices = [10.99, 20.75, 5.49]
tax_rate = 0.08
total_price = calculate_total_price(prices, tax_rate)
print(f"总价格为: ${total_price:.2f}")
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double calculateArea() {
return width * height;
}
public double calculatePerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5.0, 3.0);
System.out.println("面积: " + rectangle.calculateArea());
System.out.println("周长: " + rectangle.calculatePerimeter());
}
}
/**
* 计算数组的平均值
*
* @param {number[]} numbers - 数字数组
* @returns {number} - 平均值
*/
function calculateAverage(numbers) {
if (numbers.length === 0) return 0;
const total = numbers.reduce((acc, num) => acc + num, 0);
return total / numbers.length;
}
// 示例使用
const scores = [90, 85, 80, 95, 100];
const average = calculateAverage(scores);
console.log(`平均分数为: ${average.toFixed(2)}`);
#include <iostream>
#include <vector>
class Statistics {
public:
// 计算平均值
static double calculateMean(const std::vector<int>& numbers) {
if (numbers.empty()) return 0.0;
double sum = 0.0;
for (int num : numbers) {
sum += num;
}
return sum / numbers.size();
}
};
int main() {
std::vector<int> data = {1, 2, 3, 4, 5};
double mean = Statistics::calculateMean(data);
std::cout << "平均值: " << mean << std::endl;
return 0;
}
using System;
public class Circle
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double CalculateArea()
{
return Math.PI * Math.Pow(radius, 2);
}
public double CalculateCircumference()
{
return 2 * Math.PI * radius;
}
}
class Program
{
static void Main()
{
Circle circle = new Circle(2.5);
Console.WriteLine($"面积: {circle.CalculateArea():F2}");
Console.WriteLine($"周长: {circle.CalculateCircumference():F2}");
}
}
# 计算矩形的面积
class Rectangle
attr_reader :width, :height
def initialize(width, height)
@width = width
@height = height
end
def area
width * height
end
end
# 示例使用
rectangle = Rectangle.new(4, 5)
puts "矩形的面积为: #{rectangle.area}"
通过这些示例,可以看到优秀代码的特征,这些特征能够帮助提高代码的可读性、可维护性和可扩展性。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。