2010-10-31 60 views
1

我正在学习C++,但遇到了一个我不明白的错误。Float,Double,Char,C++错误。哪里不对?

这里是我的源代码,包含注释

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

int main() 
{ 
float h; //a float stands for floating point variable and can hold a number that is a fraction. I.E. 8.5 
double j; //a double can hold larger fractional numbers. I.E. 8.24525234 
char f; // char stands for character and can hold only one character (converts to ASCII, behind scenes). 
f = '$'; //char can hold any common symbol, numbers, uppercase, lowerver, and special characters. 
h = "8.5"; 
j = "8.56"; 

cout << "J: " << j << endl; 
cout << "H: " << h <<endl; 
cout << "F: " << f << endl; 

cin.get(); 
return 0; 
} 

编译时我收到以下错误(因为我学习个人参考。):

错误C2440: '=':不能从 转换“为const char [4]”到“浮动” 没有上下文,其中该转换是可能的

错误C2440: '=':不能从 转换 '为const char [5]' 到 '双' 没有上下文中,这种转换是可能

你们可以指向正确的方向? 我刚刚了解到const(20分钟前可能),我不明白为什么以前的程序不能正常工作。

+0

双引号内的文本是*字符串*,它与数值不同。 – GManNickG 2010-10-31 19:46:27

+0

这个问题是一个简单的语言问题,任何介绍教程将涵盖。不要以为它属于这里。 – ideasman42 2012-11-11 10:15:17

回答

10

不要在你的浮点值附近加引号。

h = "8.5"; 
j = "8.56"; 

应该

h = 8.5; 
j = 8.56; 

当你键入整型常量的值,比如intshort等,以及浮点类型,如floatdouble,您不使用语录。

例如:

int x = 10; 
float y = 3.1415926; 

您只是使用双报价时你输入一个的文本,这在C++是一个空终止const char[]阵列。

const char* s1 = "Hello"; 
std::string s2 = "Goodbye"; 

最后,当你为一个单个字符键入文字,字母或符号价值(char型的),你可以使用单引号。

char c = 'A'; 
1

doublefloat值不应该被引用。

4

当分配给浮点数或双精度值时,不能将值包含在引号中。

这些行:

h = "8.5"; 
j = "8.56"; 

应该是:

h = 8.5; 
j = 8.56; 
2

你并不需要包装浮点数在 “报价”。引号中的任何内容都是一个字符串(一个const char *)。

+1

字符串是const char数组,而不是指针。 – GManNickG 2010-10-31 20:16:28

1

删除指定给h和j的引号。