【问题标题】:Float, Double, Char, C++ Errors. What is wrong?浮点、双精度、字符、C++ 错误。怎么了?
【发布时间】:2010-10-31 19:42:43
【问题描述】:

我正在学习 C++,但遇到了一个我不明白的错误。

这是我的源代码,包括cmets(我正在学习的个人参考。)

#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]' 到 'float' 没有可以进行这种转换的上下文

还有

错误 C2440:“=”:无法从 'const char [5]' 到 'double' 没有可以进行这种转换的上下文

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

【问题讨论】:

  • 双引号内的文字是字符串文字,与数值不同。
  • 这个问题是如此简单的语言问题,任何介绍性教程都会涵盖。不要认为它属于这里。

标签: c++ compiler-construction floating-point


【解决方案1】:

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

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

应该是

h = 8.5;
j = 8.56;

当您为整数类型(如intshort 等)以及浮点类型(如floatdouble)键入文字值时,不要使用引号。

例如:

int x = 10;
float y = 3.1415926;

只有在键入 string 文字时才使用双引号,在 C++ 中它是一个以 null 结尾的 const char[] 数组。

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

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

char c = 'A';

【讨论】:

    【解决方案2】:

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

    这些行:

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

    应该是:

    h = 8.5;
    j = 8.56;
    

    【讨论】:

      【解决方案3】:

      您不需要将浮点数包含在“引号”中。引号中的任何内容都是字符串(一个 const char*)。

      【讨论】:

        【解决方案4】:

        doublefloat 值不应被引用。

        【讨论】:

          【解决方案5】:

          删除分配给 h 和 j 中的引号。

          【讨论】:

            猜你喜欢
            • 2018-07-06
            • 2015-11-22
            • 2011-04-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-24
            • 2018-02-23
            • 1970-01-01
            相关资源
            最近更新 更多