Float,Double,Char,C++错误.怎么了?

Tho*_*mas 1 c++ compiler-construction floating-point

我正在学习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;
}
Run Code Online (Sandbox Code Playgroud)

编译时收到以下错误:

错误C2440:'=':无法从'const char [4]'转换为'float'没有可以进行此转换的上下文

错误C2440:'=':无法从'const char [5]'转换为'double'没有可以进行此转换的上下文

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

Cha*_*via 10

不要在浮点值周围加上引号.

h = "8.5";
j = "8.56";
Run Code Online (Sandbox Code Playgroud)

应该

h = 8.5;
j = 8.56;
Run Code Online (Sandbox Code Playgroud)

当您为整数类型(如int,short等)以及浮点类型(如float或)键入文字值时,double不要使用引号.

例如:

int x = 10;
float y = 3.1415926;
Run Code Online (Sandbox Code Playgroud)

在键入字符串文字时只使用双引号,在C++中是字符串文本const char[].

const char* s1 = "Hello";
std::string s2 = "Goodbye";
Run Code Online (Sandbox Code Playgroud)

最后,当您为单个字符(类型char)键入文字字母或符号值时,可以使用单引号.

char c = 'A';
Run Code Online (Sandbox Code Playgroud)