Home > OS >  How do I stop my program from printing "Try again" so many times?
How do I stop my program from printing "Try again" so many times?

Time:11-18

#include <iostream>
using namespace std;

int whatcube(int y);

int main(){
int y;
cout << "Enter a perfect cube:";
cin >> y;
cout << whatcube(y);

    return 0;
}

int whatcube(int y){
    for(int i=1;i<=y; i  ){
        if(i*i*i==y){
            cout <<  "This is a perfect cube!";
        }
        else 
        cout << "Try Again.";
    }

    return 0;
}

I have very basic knowledge of coding but I want this function to print "Try Again" once if it is not a perfect cube. When the user inputs 8 for example, "Try again" appears 8 times. I also dont know why there is a zero at the end.

CodePudding user response:

This should do it.

int whatcube(int y){
    for(int i=1;i<=y; i  ){
        if(i*i*i==y){
            cout <<  "This is a perfect cube!";
            return 0;
        }
    }
    cout << "Try again.";
    return 0;
}

CodePudding user response:

You would get your program to stop printing "Try again." by revising your instructions to be more specific and precise. Your program is working exactly as designed. I would estimate that it prints out "Try again." approximately a number of times equal to the user input.

Listing what you've done well:

  • Forward declaration of your whatcube function
  • Declaring int i in your for loop
  • Incrementing i once per cycle of your for loop

It is printing out zero at the end because you've told it to, specifically and explicitly.

In addition to the 'rubber duck' method mentioned above, I would recommend mentally walking through each step, each instruction, just as if you were the computer.

CodePudding user response:

int whatcube(int y){
    for(int i=1;i<=y; i  ){
        if(i*i*i==y){
            std::cout <<  "This is a perfect cube!";
        }
        else 
           std::cout << "Try Again.";
    }
    return 0;
}

This will print "Try Again." when i is not the 3rd root of y in the loop, which is probably not what you want.

Also, your whatcube() returns an int, which will always return 0; because you code it like that. You print that return value, so it will print a zero. Looking at your code, you should make whatcube() a void function.

So, change your forward declaration to:

void whatcube(int y);

Your whatcube() function should be like this:

void whatcube(int y){
    for(int i = 1; i * i * i <= y; i  ){ // i * i * i <= y; for optimization
        if(i * i * i == y){
            std::cout <<  "This is a perfect cube!";
            return;
        }
          
    }
    std::cout << "Try Again.";
}

And call your main() function like this:

int main(){
    int y;
    std::cout << "Enter a perfect cube:";
    std::cin >> y;
    whatcube(y);
    return 0;
}
  • Related