【发布时间】:2016-02-07 23:25:33
【问题描述】:
我一直在用 C 编写代码来解决 ROSALIND 网站上的一个问题。 代码真的很简单,而且因为它很简单,所以很难纠正这个错误。(我猜) 这是我的代码:
/* A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.
An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG."
Given: A DNA string s of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s. */
#include <stdio.h>
int main(){
char nt;
int nA, nC, nG, nT;
for(int i = 0, nA = nC = nG = nT = 0; i < 1000; i++){
nt = getchar();
if(nt == 'A'){
nA++;
}else if(nt == 'C'){
nC++;
}else if(nt == 'G'){
nG++;
}else if(nt == 'T'){
nT++;
}else{
break;
}
}
printf(" %d %d %d %d", nA, nC, nG, nT);
}
当我测试这段代码时:
AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC
它应该给出:
20 12 17 21
但是我的电脑给了:
4200624 12 17 21
我已经使用 printf() 函数来查找错误所在的位置。我在离开 cicle nA = 20 之前的那一刻看到了这一点,但在它之后的那一刻 nA = 4200624 。 我能做什么?
【问题讨论】:
-
为什么将自己限制为 1000 个输入?这是一种非常不自然的代码结构方式。在
getchar返回 EOF 之前阅读更为典型。 -
如果您阅读标题,则限制为 1000 长度。