2010-10-31 56 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的引號。