簡體   English   中英

C在循環中沒有printf

[英]C doesn't printf in for loop

我是C語言的新手,正在做一些基本的事情。 我正在做一個簡單的測驗,由於某種原因,當我嘗試打印問題的選項時,它不起作用。

main.c

#include <stdio.h>
#include "app.h"

int main(void){
    startQuiz();
    return 0;
}

應用程序

#include <stdio.h>
#include <stdlib.h>


int Question(char text[100], char options[4][40], int rightAns);

void startQuiz(void){
    char q1[4][40] = {
        {'"', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '"'},
        {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'},
        {'p', 'r', 'i', 'n', 't', '(', '\'', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\'', ')'},
        {'\'', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\''}
    };

    char q2[4][40] = {
        {'g', 'e', 't', '_', 't', 'y', 'p', 'e', '(', 'x', ')'},
        {'p', 'r', 'i', 'n', 't', '(', 'x', ')'},
        {'x', '.', 't', 'y', 'p', 'e'},
        {'t', 'y', 'p', 'e', '(', 'x', ')'}
    };

    char q3[4][40] = {
        {'x'},
        {'h', 'e', 'l', 'l', 'o', '_', 'w', 'o', 'r', 'l', 'd'},
        {'e', 'x', 'e', 'c'},
        {'c', 'o', 'm', 'm', 'a', 'n', 'd'}
    };

    int Q1 = Question("what is the output of `print('hello world')`", q1, 2);
    int Q2 = Question("how to get a type of a variable?", q2, 4);
    int Q3 = Question("choose a not valid name for argument in python", q3, 3);

    printf("you got: %d / 3\n", Q1 +Q2 +Q3);
};


int Question(char text[100], char options[4][40], int rightAns){
    int ans;

    printf("\n%s.\n", text);
    for(int i; i<4; i++){
        printf("%d. %s\n", i+1, options[i]);
        // I dont want to add to i I just want to print i+1

    }printf(">>> ");
    scanf("%d", &ans);

    if(ans==rightAns){
        return 1;
    }return 0;
};

應該是一個測驗,我得到的輸出是:

在此處輸入圖片說明

它不會顯示我給它的選項:

for(int i; i<4; i++){

由於您沒有為i分配值,因此它可以有任何值。 這就是未定義的行為。 在使用變量之前,應始終確保變量具有值。

這應該修復您的代碼...

for(int i=0; i<4; i++){

另外,初始化選項的方式確實很難看懂。 您可以放入字符串,而不是列出每個單獨的字符。

char q1[4][40] = {
    "\"hello world\"",
    "hello world",
    // etc....
};

暫無
暫無

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

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