为什么变量存储的值与用户输入的值不同?

时间:2016-04-23 02:15:45

标签: c data-storage

我在设置用户输入的变量时遇到问题。我输入了一些东西并存储了另一个值。非常令人沮丧。所以任何指导都会很棒。

请注意,有很多printf(),因为我试图找出问题所在。此外,我仍然试图抓住C。

#include <stdio.h>

int vehicletype, in, out; // User Entered Info
int vehicleID[5000];
float vehicleCharge[5000]; 
int i; 

// Variables for Main Function
int q; // Loop Control
float z;

int main (){

    for(q = 1; q != 1518944; q++) {
        printf("Enter your position in the parking queue: ");
        // Take the queue entered by the user and assign it to i 
        scanf("%d\n", &i);

        // Take the user input(which is being held in the variable i) and place it into the 'i'
        //position of the ID array
        vehicleID[q] = i;

        printf("Enter the time(past 0600) you wish to start parking: \n");
        //take the time and pass it to the time function to determine roundup
        scanf("%d\n", &in);
        printf("Enter the time(before 2200) you wish to leave: \n");
        scanf("%d\n", &out);
        printf("Time in: %d\nTime out: %d\n", in, out);

    }

    return 0;

}

@ M.M我应该可以将0617输入&#34; in&#34;变量和1547用于&#34; out&#34; (我后来用它来查明它们停放了多少)但是通过打印&#34;在&#34;中检查变量时得到的输出。和&#34; out&#34;分别是1和399。

1 个答案:

答案 0 :(得分:0)

以下是一些或多或少的工作代码。我不理解1518944限制,但代码采取措施确保无论您创建了多少条目,代码都不会写出数组vehicleID的范围。它还检查一些数字的有效性,并回显其输入。某些输出的主要换行使得当通过另一个程序写入数据时输出显得半透明(随机数生成器是我用来生成数字1-5000和两次0600-2200)。

#include <stdio.h>

static int vehicleID[5000];

int main(void)
{
    for (int q = 1; q != 1518944; q++)
    {
        int in, out;
        int i;
        printf("\nEnter your position in the parking queue: ");
        if (scanf("%d", &i) != 1)
            break;

        vehicleID[q % 5000] = i;

        printf("Enter the time (past 0600) you wish to start parking: ");
        if (scanf("%d", &in) != 1)
            break;
        printf("Enter the time (before 2200) you wish to leave: ");
        if (scanf("%d", &out) != 1)
            break;
        if (in < 600 || in > 2200 || out < 600 || out > 2200 || in >= out)
            printf("Invalid times (in %.4d, out %.4d)\n", in, out);
        else
            printf("\nPosition: %d; Time in: %.4d; Time out: %.4d\n", i, in, out);
    }
    putchar('\n');

    return 0;
}

请注意,输入会被检查并回显。检查是一种至关重要的编程技术打印(echoing)是一种基本的调试技术。