首页 > 解决方案 > 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;
} 

标签: c++

解决方案


你应该做几件事:

  • 首先,您应该为自己准备一本好书C++

  • 第二件事是阅读为什么using namespace std;是一个坏主意。

  • 最后这里是你的代码修复。您需要删除分号以及删除printf(). 我还删除了using namespace std;它,使其更具可读性。

#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;
}


推荐阅读