我试图理解为什么我的一个变量userNumberInput上加了一个零。我一直在试图弄清楚,为什么这种情况会持续一段时间,却没有一个好的解决方案或解释。它只在输出文件中发生,并且似乎不会由于变量设置为0而发生。
例如,如果输入90,控制台显示90,但输出文件显示900。

#include <stdio.h>
#include <stdlib.h>
void Fibonacci (int userInputNumber);
void UserInput (int* userInputNumber);

FILE *fpOut;
int main(int argc, const char * argv[]) {
//Creating global variable for userInput to be passed from function to function
int userInputNumber = 0;

//Opening file for writing output to
if (!(fpOut = fopen("csis.txt", "w"))) {
    printf("csis.text could not be opened for output");
    exit(1);
}

//Calling two functions and passing appropriate vaiables to each
UserInput(&userInputNumber);
Fibonacci(userInputNumber);

fclose(fpOut);
return 0;
}

void UserInput (int* userInputNumber) {
//Asks the user for a number for the generator
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);

//While the user continues to enter a negative number it forces the user to enter a new number
while (*userInputNumber < 0) {
    printf("Invalid user input, enter a positive number\n\n");
    fprintf(fpOut,"Invalid user input, enter a positive number\n\n");
    printf("Enter a number into the Fibonacci Generator: ");
    scanf("%d", &*userInputNumber);
    fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
}
}

void Fibonacci (int userInputNumber) {
//Defines variables used in this function
int firstNumber, secondNumber, i, seriesNumber, length;
firstNumber = 0;
secondNumber = 1;
seriesNumber = 0;
i = 0;
length = 0;

//For loop that adds the two previous number in the series and prints it and then updates the previous numbers
for (i = 0; seriesNumber < userInputNumber; i++) {
    if (i <= 1) {
        seriesNumber = i;
        length++;
    } else {
        seriesNumber = firstNumber + secondNumber;
        firstNumber = secondNumber;
        secondNumber = seriesNumber;
        length++;
    }

    //Statement to break the loop when the next number in the series goes above the user input
    if (seriesNumber > userInputNumber) {
        length -= 1;
        break;
    }

    //Printing the sequence
    printf("%d\n",seriesNumber);
    fprintf(fpOut,"%d\n",seriesNumber);
}

//Printing the length of the sequence
printf("Length of the sequence: %d", length);
fprintf(fpOut,"Length of the sequence: %d", length);
}

最佳答案

您必须在打印输入的值后打印一个换行符,或0,这是序列的第一个项,似乎附加到输入后。
试着同时改变两者

fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);


fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d\n", *userInputNumber);

关于c - 在控制台中不可见的输出文件中添加了0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36075710/

10-11 18:42