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. I know void function don't return any value so I put cout inside the function and I call is correctly
#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. You can not mod a number with 0. Division by zero is not allowed.
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.
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
. Doing the modulo %
operation with a right-hand-side operand of 0
is not going to work. Start the loop from i = 1
or something else >0
.
Lastly, your program will terminate in main
at the return 0;
right after the first Print
. This means that most of your main
won't actually be executed. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.