简体   繁体   English

无效 function 不打印

[英]Void function doesn't print

I am trying to write a code to print values using function and the program doesn't print anything and I don't know why.我正在尝试编写代码以使用 function 打印值,但程序不打印任何内容,我不知道为什么。 I know void function don't return any value so I put cout inside the function and I call is correctly我知道 void function 不返回任何值,所以我将 cout 放在 function 内,我调用是正确的

#include <iostream>
using namespace std;

void Print(int n){
    for (int i = 0; i <= n; i++){
        if (n%i == 0){
            cout << i << ' ';
        }
    }
    cout << endl;
}
    
int main(){
    int x;
    cin >> x;
    Print(x);
    return 0;
}

Start your loop from 1 in Print function.Print function 中的 1 开始循环。 You can not mod a number with 0. Division by zero is not allowed.您不能用 0 修改数字。不允许除以零。

When you run your program, it wont print anything.当你运行你的程序时,它不会打印任何东西。 You have to enter a number first, then press Enter/Return, and then it should print something.您必须先输入一个数字,然后按 Enter/Return,然后它应该会打印一些东西。

Assuming you do this and it still does not print, that will be because your Print has a loop that starts from i = 0 , and you then do n % i .假设您这样做并且它仍然不打印,那将是因为您的Print有一个从i = 0开始的循环,然后您执行n % i Doing the modulo % operation with a right-hand-side operand of 0 is not going to work.使用右侧操作数0进行模%运算是行不通的。 Start the loop from i = 1 or something else >0 .i = 1或其他>0开始循环。

Lastly, your program will terminate in main at the return 0;最后,您的程序将在return 0;时在main中终止; right after the first Print .就在第一个Print之后。 This means that most of your main won't actually be executed.这意味着您的大部分main内容实际上不会被执行。 This is probably intentional, but keep that in mind.这可能是故意的,但请记住这一点。

Fix these issues and make sure you enter a number into your program when it runs that is valid, like 12 , and it should print something.修复这些问题并确保在程序运行时在程序中输入一个有效的数字,例如12 ,它应该会打印一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM