【发布时间】:2016-01-29 01:43:40
【问题描述】:
我只是 C 编程的初学者。请帮助我解决以下问题。
问题:一个程序搜索包含一系列字符的给定数组。这些字符被限制为字母 A、G、T 或 C。序列中的最后一个字符设置为代码 0,以便于检测到结尾。
在这里找不到我做错了什么,但不断出错。
/*A program that searches through a given array that contains a sequence of characters. These characters are restricted
to be the letters A, G, T, or C. The last character in the sequence is set to be the code 0, so that the end is easily
detected. That array should be declared and initialized.*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void input_sequence(int length,char input[]);
void search(char C[],char DNA[],int length);
int main(void) {
//Given array
char DNA[] = {'A', 'G', 'C', 'G', 'G', 'G', 'A', 'C', 'C', 'G', 'T', 'C',
'C', 'C', 'G', 'A', 'C', 'A', 'T', 'T', 'G', 'A', 'T', 'G',
'A', 'A', 'G', 'G', 'G', 'T', 'C', 'A', 'T', 'A', 'G', 'A',
'C', 'C', 'C', 'A', 'A', 'T', 'A', 'C', 'G', 'C', 'C', 'A',
'C', 'C', 'A', 'C', 'C', 'C', 'C', 'A', 'A', 'G', 'T', 'T',
'T', 'T', 'C', 'C', 'T', 'G', 'T', 'G', 'T', 'C', 'T', 'T',
'C', 'C', 'A', 'T', 'T', 'G', 'A', 'G', 'T', 'A', 'G', 'A',
'T', 'T', 'G', 'A', 'C', 'A', 'C', 'T', 'C', 'C', 'C', 'A',
'G', 'A', 'T', 'G', '\0'};
int length,i=0,k;
/*Program should repeatedly ask the user for two things: the length of a search sequence,
and the search sequence itself*/
/*The program should terminate when the length of the input sequence is zero or less*/
do{
printf("Enter length of DNA sequence to match: ");
scanf("%d",&length);
Search sequence array
char input[length];
//input sequence length has to be >0
if(length>0){
input_sequence(length,input[]);
/*The elements of the search sequence may take on one of five characters: A,G,T,C and *. The
meaning of the ‘*’ character is that it matches all four nucleotides: A,G,T and C.*/
for(i=0; i<length; i++){
k=0;
if(input[i]!='A'&&input[i]!='G'&&input[i]!='T'&&input[i]!='C'&&input[i]!='*'){
printf("Erroneous character input ’%c’ exiting\n",input[i]);
k=1;
}
if(k==1)
break;
}
if(k==0){
search(input,DNA,length);
}
k=0;
}
}
while(length>0);
printf("Goodbye");
return (EXIT_SUCCESS);
}
//Function to search for input sequence in the given array
void search(char C[],char DNA[],int length){
int numFound = 0,i,foundIndex;
bool found = false;
for(i=0;i<length && !found;i++) {
int n=0;
char temp=C[i];
if (temp==DNA[i]) {
numFound++;
if (numFound == length) {
found = true;
foundIndex = i - (length-1);
}
}
else numFound = 0;
}
if (found)
printf("Match of search sequence found at element %d\n",foundIndex);
}
void input_sequence(int length,char input[]){
int i;
printf("Enter %d characters (one of AGTC*) as a search sequence: ",length);
for(i=0; i<length; i++){
scanf(" %c", &input[i]);
}
}
【问题讨论】:
-
请按 Ctrl+A 并删除并重新开始。嵌套的
if语句真是一团糟,没有人会那样做。另外,问题是什么? -
问题:一个程序搜索包含一系列字符的给定数组。这些字符被限制为字母 A、G、T 或 C。序列中的最后一个字符设置为代码 0,以便于检测到结尾。
-
这不是我的问题,如果您有问题并想解决它,请在这里问。
-
搜索排列
-
您在寻找
strstr()吗?
标签: c arrays function for-loop do-while