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;
}
解决方案
你应该做几件事:
首先,您应该为自己准备一本好书
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;
}
推荐阅读
- arrays - 这个函数的返回值是什么
- python - 无法使用 selenium 从页面中名为“heading”的每个类中获取数据
- asp.net-mvc - 首先生成下拉asp.net mvc代码
- javascript - JS 字符串字面量
- javascript - 为什么空数组通过 if(array !== []) 检查
- sql - mariadb json中正确使用json_table
- python - 使用 python-crontab 的多个作业
- python - Flask URL 像这样“/api/hello”工作,但不像这样“/api/hello/”
- regex - 匹配浮点数或整数的正则表达式,可以是正数或负数
- html - 使用 get 方法将表单绑定到 GetMapping 控制器时出现问题