gpt4 book ai didi

c - 什么是更好的方法来做到这一点?摩尔斯电码程序

转载 作者:太空宇宙 更新时间:2023-11-04 01:57:15 25 4
gpt4 key购买 nike

我用 C 语言为我的家庭作业编写了一个程序,该程序应该接收文本并通过 LED 将其翻译成摩尔斯电码。要知道,我已经将 LED 的预定闪烁长度替换为:“这是一个 __。”这就像现在一样有效,我会得到充分的信任,但我的问题是是否有更好的方法来做到这一点?我知道必须有,而不是使用所有那些“if”语句。但我是 C 的初学者。(这段代码的唯一缺点是它很长而且你不能输入空格。)它目前的工作方式是它接受一个字符串并将它分解成单独的字母,然后在 'for'循环检查这些单独的字母是否有相应的摩尔斯电码。让我知道你的想法。

// MorseCode_Attempt1.cpp : Defines the entry point for the console application.
//

include<stdio.h>
include<conio.h>
include<string.h>


void main() {

char str[500];

printf("Enter a string you want in Morse Code with underscores as spaces: ");
scanf("%s", &str);

int i;
int stringLength = strlen(str);

for (i = 0; i < stringLength; i++) {
printf("\n[%c]\n", str[i]);


if (str[i] == 'a') {
printf("\nIt is an a.\n");
}

if (str[i] == 'b') {
printf("\nIt is an b.\n");
}

if (str[i] == 'c') {
printf("\nIt is an e.\n");
}

if (str[i] == 'd') {
printf("\nIt is an d.\n");
}

if (str[i] == 'e') {
printf("\nIt is an e.\n");
}

if (str[i] == 'f') {
printf("\nIt is an f.\n");
}

if (str[i] == 'g') {
printf("\nIt is an g.\n");
}

if (str[i] == 'h') {
printf("\nIt is an h.\n");
}

if (str[i] == 'i') {
printf("\nIt is an i.\n");
}

if (str[i] == 'j') {
printf("\nIt is an j.\n");
}

if (str[i] == 'k') {
printf("\nIt is an k.\n");
}

if (str[i] == 'l') {
printf("\nIt is an l.\n");
}

if (str[i] == 'm') {
printf("\nIt is an m.\n");
}

if (str[i] == 'n') {
printf("\nIt is an n.\n");
}

if (str[i] == 'o') {
printf("\nIt is an o.\n");
}

if (str[i] == 'p') {
printf("\nIt is an p.\n");
}

if (str[i] == 'q') {
printf("\nIt is an q.\n");
}

if (str[i] == 'r') {
printf("\nIt is an r.\n");
}

if (str[i] == 's') {
printf("\nIt is an s.\n");
}

if (str[i] == 't') {
printf("\nIt is an t.\n");
}

if (str[i] == 'u') {
printf("\nIt is an u.\n");
}

if (str[i] == 'v') {
printf("\nIt is an v.\n");
}

if (str[i] == 'w') {
printf("\nIt is an w.\n");
}

if (str[i] == 'x') {
printf("\nIt is an x.\n");
}

if (str[i] == 'y') {
printf("\nIt is an y.\n");
}

if (str[i] == 'z') {
printf("\nIt is an z.\n");
}

if (str[i] == '_') {
printf("\nIt is a SPACE.\n");
}

}

return 0;

}

最佳答案

当你使用很多if's 并且在一场比赛之后你必须继续前进然后使用if-else-if ladder因此,如果找到“b”,那么它就不会检查所有其他条件。

但这里最好的解决方案是 switch case .

在您的for-loop 中尝试这样的事情。

switch (str[i])
{
case 'a':
printf("\nIt is an a.\n");
break;

case 'b':
printf("\nIt is a b.\n");
break;

/* etc. etc. etc.*/

default:
//default will work when the input to the switch->here str[i] does not match any case.
printf("\nNot a character or space!");
break;
}

关于c - 什么是更好的方法来做到这一点?摩尔斯电码程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com