gpt4 book ai didi

无法让字符串搜索正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:04 24 4
gpt4 key购买 nike

我正在编写一个简单的程序,从控制台获取用户输入以计算电阻器的电阻值,其中一部分涉及将用户输入与预定字符串列表进行比较。

我已经弄清楚了其中的大部分内容(至少我是这么认为的),但是每当我调用“搜索”函数时,它应该返回与输入匹配的字符串数组的索引,否则返回 -1 .问题是,每当我在适当的程序中调用它时,它总是返回 -1,因此即使不是,程序也会打印“无效颜色”。我不确定问题出在哪里,我想知道我能做些什么。

这是有问题的程序:

#include <stdio.h>
#include <math.h>
#include <string.h>

char COLOR_CODES[10][7] = {"black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "gray", "white"};
int COMPARE_LIMIT = 7;

int search(char array[10][7], int size, char target[7]);

int main(void)
{
//used for repeating input menu
int menu = 0;
char menuChoice = 0;

//string variables hold input colors.
char band1[7];
char band2[7];
char band3[7];

//int variables hold int values of subscript for bands 1-3
int value1;
int value2;
int value3;

//value of resistor in ohmn
int ohms;

//holds value of multiplier for third band
int powerMultiplier;

while(menu == 0)
{
printf("Enter the colors of the resistor's three bands,\n");
printf("beginning with the band nearest the end. Type\n");
printf("the colors in lowercase letters only. NO CAPS\n");
printf("OR SPACES.\n");

printf("Band 1:");
scanf("%s", &band1);
printf("Band 2:");
scanf("%s", &band2);
printf("Band 3:");
scanf("%s", &band3);

if(search(COLOR_CODES, 10, band1) == -1)
{
printf("Invalid Color: %s\n", band1);
}

else if(search(COLOR_CODES, 10, band2) == -1)
{
printf("Invalid Color: %n\n", band2);
}

else if(search(COLOR_CODES, 10, band3) == -1)
{
printf("Invalid Color: %s\n", band3);
}

else
{
value1 = search(COLOR_CODES, 10, band1);
value2 = search(COLOR_CODES, 10, band2);
value3 = search(COLOR_CODES, 10, band3);

powerMultiplier = (int)pow(10, value3);

ohms = (value1 * 10) + value2;
ohms = ohms * powerMultiplier;

if(ohms < 1000)
{
printf("Resistance value: %s ohms", ohms);
}

else
{
int kiloOhms = (ohms / 1000);
printf("Resistance value: %s kilo-ohms", kiloOhms);
}

printf("Do you want to decode another resistor? (y/n)");
scanf("%c", &menuChoice);

while(menuChoice != 'y' && menuChoice != 'Y' && menuChoice != 'n' && menuChoice != 'N')
{
if(menuChoice != 'Y' && menuChoice != 'y')
{
if(menuChoice == 'N' || menuChoice == 'n')
{
menu = 0;
}

else
{
printf("Invalid choice.");
}
}
}
}
}

return 0;
}

//returns the subscript of array[][] that matches target[].
int search(char array[10][7], int size, char target[7])
{
int n;
for (n = 0; n < size; n++)
{
if (strncmp(array[n], target, COMPARE_LIMIT) == 0)
{
return n;
}

else
{
return -1;
}
}
}

最佳答案

您的 search() 函数在仅查看列表中的第一项后返回 -1。所以它可能会找到 black 但不会找到其他任何东西。建议修改如下:

int search(char array[10][7], int size, char target[7])
{
int n;
for (n = 0; n < size; n++)
{
if (strncmp(array[n], target, COMPARE_LIMIT) == 0)
{
return n;
}
}
return -1;
}

这样,for 循环将在确定您键入的内容未找到并返回 -1 之前运行完成。

关于无法让字符串搜索正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341223/

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