116,110
社区成员




% 计算票价
function fare = calculate_fare(distance)
if distance == 2
fare = 2;
elseif distance > 2 && distance <= 4
fare = 3;
elseif distance > 4 && distance <= 6
fare = 4;
else
fare = -1; % 表示无效的距离
end
end
% 播放音频
function play_audio(text)
fprintf('正在播放语音:%s\n', text);
% 将文本转换为音频
fs = 44100; % 采样率
t = 0:1/fs:1; % 时间向量
freq = 300; % 生成的音频频率
audio_data = sin(2*pi*freq*t); % 生成简单的音频数据
% 创建 audioplayer 对象并播放音频
player = audioplayer(audio_data, fs);
play(player);
% 等待音频播放完成
pause(player.TotalSamples/fs);
end
% 主函数
function subway_program()
a = input('请输入乘车人信息:', 's');
fprintf('欢迎%s乘坐地铁\n', a);
play_audio(sprintf('欢迎%s乘坐地铁', a));
b = a;
fprintf('%s\n', b);
str = b;
% 打开文件
file = fopen('test.txt', 'w');
if file == -1
fprintf('无法打开文件。\n');
return;
end
% 写入字符串
fprintf(file, '%s', str);
% 关闭文件
fclose(file);
fprintf('成功写入文件。\n');
% 打开文件
fp = fopen('station.txt', 'r');
% 检查文件是否成功打开
if fp == -1
fprintf('无法打开文件\n');
return;
end
fprintf('地铁站列表:\n');
stations = {};
while ~feof(fp)
buffer = strtrim(fgetl(fp));
fprintf('%s\n', buffer);
stations = [stations, buffer];
end
% 关闭文件
fclose(fp);
c = input('请输入上车站:', 's');
fprintf('上车站为:%s\n', c);
d = input('请输入下车站:', 's');
fprintf('下车站为:%s\n', d);
% 查找出发站和终点站的索引
start_index = find(strcmp(stations, c));
end_index = find(strcmp(stations, d));
if isempty(start_index) || isempty(end_index)
fprintf('输入的站点有误\n');
return;
end
fprintf('途径车站列表:\n');
if start_index < end_index
for i = start_index:end_index
fprintf('第%d站:%s\n', i - start_index + 1, stations{i});
play_audio(sprintf('第%d站:%s', i - start_index + 1, stations{i}));
end
else
for i = start_index:-1:end_index
fprintf('第%d站:%s\n', start_index - i + 1, stations{i});
play_audio(sprintf('第%d站:%s', start_index - i + 1, stations{i}));
end
end
% 计算距离并显示票价
distance = abs(start_index - end_index) + 1;
fare = calculate_fare(distance);
if fare == -1
fprintf('无效的距离,无法计算票价。\n');
else
fprintf('%s乘坐地铁结束,票价为%d元\n', a, fare);
play_audio(sprintf('%s乘坐地铁结束,票价为%d元', a, fare));
end
end
% 在此处调用 subway_program 函数来运行程序
subway_program();