统计票数的程序可以根据不同的编程语言和需求有不同的实现方式。以下是几种常见编程语言的示例代码:
Python 示例
```python
使用字典存储候选人和票数
candidates = { '张三': 0, '李四': 0, '王五': 0 }
def vote(name):
if name in candidates:
candidates[name] += 1
return f'投票成功!{name}当前得票数:{candidates[name]}'
else:
return '咦?这个人不在候选名单里哦'
测试投票
print(vote('张三'))
print(vote('李四'))
print(vote('张三'))
投票结果统计
def show_results():
sorted_results = sorted(candidates.items(), key=lambda x: x, reverse=True)
result_str = ', '.join([f'{name}: {votes}' for name, votes in sorted_results])
print(f'投票结果: {result_str}')
show_results()
```
Java 示例
```java
import java.util.*;
public class VotingSystem {
private Map private Set public VotingSystem() { options = new HashMap<>(); voters = new HashSet<>(); } public void addOption(String option) { if (!options.containsKey(option)) { options.put(option, 0); } } public String vote(String voterId, String option) { if (voters.contains(voterId)) { return "你投过票了,别想耍小聪明~"; } if (!options.containsKey(option)) { return "这个选项不存在哦"; } options.put(option, options.get(option) + 1); voters.add(voterId); return f"投票成功! 你选择了: {option}"; } public void showResults() { int total = 0; for (Map.Entry total += entry.getValue(); } System.out.println("总票数: " + total); for (Map.Entry System.out.println(entry.getKey() + ": " + entry.getValue() + "票"); } } public static void main(String[] args) { VotingSystem vs = new VotingSystem(); vs.addOption("张三"); vs.addOption("李四"); vs.addOption("王五"); System.out.println(vs.vote("user1", "张三")); System.out.println(vs.vote("user1", "李四")); System.out.println(vs.vote("user1", "张三")); System.out.println(vs.vote("user2", "王五")); vs.showResults(); } } ``` C++ 示例 ```cpp include include