簡體   English   中英

為什么我在 C 語言的 printf 中得到非常大的 output?

[英]Why I get very huge output in printf on C language?

這是我的代碼,我想計算機器人和怪物之間的距離,但是 output “水平和垂直”是錯誤的

#include <stdio.h> 

void findPos(char *dir, int a, int b)
{
    int up = 0, down = 0;
    int left = 0, right = 0;
    int i,x,y;

    for (i = 0; dir[i] != '\0' ; i++) {
        //Counts each direction
        if (dir[i] == 'U' || dir[i] == 'u')
            up++;
        else if (dir[i] == 'D' || dir[i] == 'd')
            down++;
        else if (dir[i] == 'L' || dir[i] == 'l')
            left++;
        else if (dir[i] == 'R' || dir[i] == 'r')
            right++;

          //In case of illegal character in the string
        else
        {
            printf("Position Unable to Find, Enter Correct Direction.");
            break;
        }
    }

    //Final position of robot
    x = right - left;
    y = up - down;

    printf("Final Position of the Robot: (");
    printf("%d", x);
    printf(",%d", y);
    print(")");

    printf("\nposition between robot and monster");
    printf("\nhorizontal: %d", a-x);
    printf("\nvertikal: %d", b-y);

}

int main()
{
    char *dir;
    int a,b,t;

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /* Print 2 random numbers from 0 to 100 */
    a = rand() % 100;
    b = rand() % 100;

    printf("\nCoordinate of monster: ");
    printf("(%d,", a);
    printf("%d)", b);
    //Input the direction string
    printf("\nEnter the Direction String: ");
    scanf("%s", &dir);
    //Function call to calculate position
    findPos(&dir, a,b);

    return 0;
}

這是 output

Coordinate of monster: (5,47)  
Enter the Direction String: UURRRRRLLL
Final Position of the Robot: (2,2)  
position between robot and monster  
horizontal: 19530  
vertikal: 1280463440

似乎您的程序表現出未定義的行為,實際上您很幸運它沒有崩潰,從未分配過dir 你可能想在使用之前calloc它,也刪除&中的scanf ,事實上移動到fgets除非傾向於使用scanf

   printf("\nEnter the Direction String: ");
        scanf("%s", dir);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM