0

我正在学习 C++,并创建了一个使用 char 的简单 void 函数。我在顶部对函数进行了原型设计,在 int main 中定义它并尝试输出“你的名字是”x。有人能告诉我为什么它只告诉我“你的名字是”而不是 x (john) 部分吗?

#include <iostream>
#include <cstdlib>
#include <cmath>

void myfun(char x);

int main() {
using namespace std;

char John;
myfun(John);

system("pause");
return 0;
}

void myfun(char x) {
using namespace std;

cout << "Your name is " << x << endl;
}

想知道为什么这会被否决...也许我应该停止尝试学习 C++,因为显然没有人想帮助其他人学习

4

3 回答 3

2

它不起作用的主要原因是因为您没有为John. John只是您用来识别的变量名。

如果你想显示,Your name is John那么你必须给它一个值,如果你想让它打印出一个字符串,它应该是 aString而不是 a char

例子:

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

void myfun(string x);

int main() {
  string John = "John";
  myfun(John);

  system("pause");
  return 0;
}

void myfun(string x) {  
  cout << "Your name is " << x << endl;
}

最后,你不需要把using namespace std每个函数都放进去,你可以简单地把它放在上面或你的代码上。

于 2013-11-09T06:42:27.977 回答
0

编辑代码:

#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

void myfun(std::string x);

int main() {

std::string name = "John";
myfun(name);

system("pause");
return 0;
}

void myfun(str::string x) {
cout << "Your name is " << x << endl;
}

尝试这个。使用字符串使用 std::string 数据类型。

于 2013-11-09T06:39:17.517 回答
0

看起来主要问题是您的印象是变量 John 已初始化为“John”。关闭有两个原因。首先,变量 John 没有被初始化(它没有被赋值)。其次,变量 John 是一个字符,这意味着它只能包含一个字符。尝试改变 char John;对此:字符串名称=“约翰”;

然后替换对变量的引用。

第一次程序员的一个大问题是假设他们的变量名称与变量存储的实际值有任何关系。我可以这样做: int doody = 3.14;

doody 将有一个不错的 pi 估计。我也可以这样做:int pi = 3.14;

然后 pi 会有一个不错的 pi 估计。

仅仅因为你命名一个变量并不意味着它包含与该名称相关的任何数据。话虽如此,您应该远离命名变量之类的东西,例如“x”等等,因为这不是描述性的。变量的名称应该描述它的内容,但是开发人员应该知道变量的名称并不能确定它的内容(是的,模棱两可......有点)

于 2013-11-09T07:07:14.453 回答