2016-07-27 46 views
0

不幸的是,我试图从用户定义的函数中检索数据,我无法这样做。无法从用户定义的函数获取值

例如,我有两个用户定义函数是

为getPosition:为了知道基于用户输入在图上的位置

printPosition:为了显示信息基于在图表上

因此,例如,我getPosition的位置,我做了一个简单的if else语句

char getPosition (float x, float y){ 

char position; 

if (x > 0 && y > 0) 

    position = 1; 

else if (x < 0 && y > 0) 

    position = 2; 

...... 

return position; 

接着,我尝试printPosition使用开关壳体

switch(position) 
{ 

    case '1' : cout << "==> (" << x << ", " << y << ") is above X-axis" << endl; 
       cout << "==> It is at first quadrant" << endl; 
       break; 

    case '2' : cout << "==> (" << x << ", " << y << ") is above X-axis" << endl; 
       cout << "==> It is at second quadrant" << endl; 
       break; 

    ....... 

} 

所以具有两个用户定义函数后,我试图在getPosition呼吁的值,以从printPosition

printPosition(x, y, getPosition(x,y)); 
数据打印出来

但是,它不会产生任何输出。这是为什么。

在此先感谢您的帮助。

+0

请** [编辑] **用[MCVE]或您的问题[SSCCE(短的,独立的,正确的示例)](HTTP:// SSCCE。 org) – NathanOliver

+0

这听起来像你可能需要学习如何使用调试器来遍历代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

+0

如果产生错误,我很乐意进行调试任何错误,不幸的是,我设法编译它们,使我很难找出问题所在。 –

回答

4

要么改变:

position = 1; 
position = 2; 
... 

要:

position = '1'; 
position = '2'; 
... 

或更改:

case '1': 
case '2': 
... 

要:

case 1: 
case 2: 
... 
+0

...因为''1''是一个字符,其对应的ASCII(或utf8)代码是49,所以''1'!= 1' ... –

+0

为什么没有函数返回int? –

+0

@DanKorn它并不重要。它也可以返回一个枚举,只要它匹配'case's。 –

0

position = '1'; 
position = '2'; 

你也应该始终有一个默认的说法在switch语句,因为这有助于你明白,没有一个case语句被执行,调试的简单方法。

可以实现这样的:

switch(position) 
{ 
case '1': 
//whatever 
break; 
case '2': 
//whatever 
break; 
default: 
//Can have a message like: 
cout << "The value was not in any of the case statements" << endl; 
//No break needed for default statements 
} 
相关问题