初学者C循环功能

Fab*_*oni 0 c function

我刚刚开始冒险进入来自PHP的C语言.printf()从另一个函数调用时,我遇到了函数问题:

#include <stdio.h>

void printloop (int valx) {
    int x;
    for (x = valx; x < 5; x++) {
        printf("Value of x is: %d\n", x);
    }
}

int main() {
    printloop(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

该程序将编译并运行,但屏幕上没有输出.

Cro*_*zin 6

当你printloop5for循环调用函数时,本质上就变成了

for (x = 5; x < 5; x++) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

而且x < 5将永远是正确的.


我猜你的意思是什么

for (x = 0; x < valx; x++) {
    //...
}
Run Code Online (Sandbox Code Playgroud)


J M*_*len 5

这里有什么问题,你的逻辑是说5 <5,这是错误的.你的for循环没有执行,因为当你调用printloop函数时, printloop(5);它传递整数值5.

void printloop (int valx) {
int x;
for (x = valx; x < 5; x++) {
    printf("Value of x is: %d\n", x);
}
Run Code Online (Sandbox Code Playgroud)

您的printloop函数接收值为5,将函数内部的x设置为x = 5.

当您的for循环执行时,您将拥有

void printloop (int valx) {
    int x = 5;
    for (5 = valx; 5 < 5; 5++) {
        printf("Value of x is: %d\n", x);
    }
}
Run Code Online (Sandbox Code Playgroud)

for循环将看到5 <5,这是错误的,因而环路将不会执行.

我想你想说的是

#include <stdio.h>

void printloop (int valx) {
    int x;
    for (x = 0; x < valx; x++) {
        printf("Value of x is: %d\n", x);
    }
}

int main() {
    printloop(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

哪个会输出:

Value of x is: 0
Value of x is: 1
Value of x is: 2
Value of x is: 3
Value of x is: 4
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的,并保持良好的工作!