Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float, Double, Char, C++ Errors. What is wrong?

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"
#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;
}

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.

like image 342
Thomas Avatar asked Aug 26 '26 08:08

Thomas


2 Answers

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';
like image 113
Charles Salvia Avatar answered Aug 27 '26 22:08

Charles Salvia


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;
like image 26
Justin Niessner Avatar answered Aug 27 '26 21:08

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!