C - ()cicle之后的错误

Moo*_*ker 4 c for-loop

我一直在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);
}
Run Code Online (Sandbox Code Playgroud)

当我测试这段代码时:

AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC
Run Code Online (Sandbox Code Playgroud)

它应该给:

20 12 17 21
Run Code Online (Sandbox Code Playgroud)

但我的电脑给出:

4200624 12 17 21
Run Code Online (Sandbox Code Playgroud)

我已经使用printf()函数来查找错误所在的位置.我已经看到了在离开cA nA = 20之前的那一刻,但是在它之后的那一刻nA = 4200624.我能做什么?

小智 10

我相信这是因为您正在重新声明for标头中的变量,您将变量设置为0.由于您在i之后声明了nA,因此您创建了一个具有相同名称但具有不同范围的新变量.这个只在for循环中可见,但在结束后被销毁.由于您的分配链,其他变量已正确初始化.即它们是初始化的,而不是重新声明的.在您声明它们的同一行中初始化变量将解决问题.