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

标签 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 我应该能够在“in”变量中输入 0617,在“out”变量中输入 1547(稍后我用它来查明他们停了多少车),但是通过打印“检查变量时得到的输出” in”和“out”分别是1和399。

最佳答案

这里有一些或多或少的工作代码。我不明白 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;
}

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

关于c - 为什么变量存储的值与用户输入的值不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805899/

相关文章:

swift - 为什么我的代码没有将数据保存到 Kinvey 后端?

c - 这些局部变量地址背后的基本原理是什么?

c - Vim 关键字补全

c - 在c中修剪字符串时遇到麻烦

c - C 中的大整数?

database - 在哪里保存视频文件 - 数据库或磁盘

ios - 在iPhone上存储应用程序数据的最佳方法是什么?

java - 是否有任何库或组件可以处理用户生成内容的存储和快速检索?

c - 我的 strcmp 函数有什么问题?

c - 带有多个命令的 C Shell,段错误(核心转储)