I am learning C++, but I ran into an error which I don't understand.
Here is my source code, comments included (personal reference as I am learning.)
#include "stdafx.h"
#incl开发者_C百科ude <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;
}
I receive the following errors when compiling:
error C2440: '=' : cannot convert from 'const char [4]' to 'float' There is no context in which this conversion is possible
And
error C2440: '=' : cannot convert from 'const char [5]' to 'double' There is no context in which this conversion is possible
Can you guys point me in the right direction? I just learned about const (20 minutes ago maybe) and I don't understand why this previous program isn't working properly.
Don't put quotation marks around your floating point values.
h = "8.5";
j = "8.56";
should be
h = 8.5;
j = 8.56;
When you type literal values for integral types, like int
, short
, etc., as well as floating point types like float
or double
, you don't use quotations.
For example:
int x = 10;
float y = 3.1415926;
You only use double-quotations when you are typing a string literal, which in C++ is a null-terminated const char[]
array.
const char* s1 = "Hello";
std::string s2 = "Goodbye";
Finally, when you are typing a literal alphabetic or symbolic value for a single character (of type char
), you can use single quotations.
char c = 'A';
When assigning to a float or double, you can't wrap the values in quotes.
These lines:
h = "8.5";
j = "8.56";
Should be:
h = 8.5;
j = 8.56;
You don't need to wrap floating point numbers in "quotes". Anything in quotes is a string (a const char*).
double
and float
values should not be quoted.
Remove the quotes in the assignements to h an j.
精彩评论