Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

c++ - Why is my code stopping prematurely? what have i done wrong?

I'm just starting so I'm trying to write a program which determine if a number is positive or negative.

#include <iostream>;

int step_function(int x) {
    
    int result = 0; 
    
    if (x > 0) 
        result = 1;
    else if (x < 0) 
        result = -1;
    else 
        result = 0;

    return result;
}

using namespace std;

int main() {
    
    int num;
    
    cout<< "please enter number : ";
    cin >> num;
    
    int a = step_function(num); 
    
    if (a == 1) 
        printf("%d is positive", num);
    else if (a == -1) 
        printf("%d is negative", num);
    else 
        printf(" it is zero");

    return 0;
} 
question from:https://stackoverflow.com/questions/65713116/why-is-my-code-stopping-prematurely-what-have-i-done-wrong

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a few things you should do:

  • First things first you should get yourself a Good Book for C++.

  • Second thing is read why using namespace std; is a bad idea.

  • Lastly here is your code fixed. You needed to remove the semicolon as well as removing the printf(). I also removed the using namespace std; which made it more readable.

#include <iostream>

int step_function(int); //Function prototype

int main() {
    int num;
    std::cout << "please enter number : ";
    std::cin >> num;
    int a = step_function(num);
    if (a == 1)
        std::cout << num << " is postive"; 
    else if (a == -1)
        std::cout << num << " is negative";
    else std::cout <<" it is zero";

    return 0;
}


int step_function(int x) 
{
    int result = 0;
    if (x > 0) result = 1;
    else if (x < 0) result = -1;
    else result = 0;

    return result;
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...