2016-08-14 120 views
1
#include <iostream> 
#include <math.h> 
#include "stdafx.h" 

using namespace std; 

int main() 
{ 
    float a, b; 
    cout << "Enter The Number: "; 
    cin >> a; 
    b = sqrt(a); 
    cout << "The Square Root of The Number Is: " << b; 
    return 0; 
} 

編譯器給出了錯誤:這段C++代碼有什麼問題?

consoleapplication1.cpp(10): error C2065: 'cout': undeclared identifier 
consoleapplication1.cpp(11): error C2065: 'cin': undeclared identifier 
consoleapplication1.cpp(12): error C3861: 'sqrt': identifier not found 
consoleapplication1.cpp(13): error C2065: 'cout': undeclared identifier 

請告訴我的錯誤,也就是爲什麼我包括「stdafx.h中」,爲什麼它在引號?使用Visual Studio 2015.級別:初學者

+4

您可以閱讀關於'stdafx.h' [here](http://stackoverflow.com/questions/4726155/whats-the-use-for-stdafx-h-in-visual-studio) – Rakete1111

+5

TL; DR :將'#include「stdafx.h」'向上移動,所以它是源文件中的第一條(非註釋)行。 –

+2

我相信您展示的錯誤不是唯一的錯誤。在此之前你應該有一個,關於預先編譯的頭文件「stdafx.h」沒有被包含在第一個。 –

回答

2

簡單移動#include "stdafx.h"在文件的頂部,您的代碼將被編譯。

stdafx.h包含預編譯頭文件,如果你想刪除它,你必須在項目屬性中禁用它。

更好的選擇是禁用它同時創造在Visual Studio新的項目

文件 - >新建項目 - >選擇你的設置和類型確定 - >下一步 - >點擊這裏取消「預編譯頭」 - >完成

+0

爲什麼「更好」選項會禁用預編譯頭文件?學習如何使用它會更有意義嗎?這並不難,而且可以節省很多時間。 –

+0

只有預編譯頭文件沒有更改時,預編譯頭文件纔會節省時間。只有在包含大量包含文件的情況下,時間纔有意義。 –

+0

對。當你構建一個Windows應用程序時(就像Visual Studio常見的那樣),你需要包含所有的Windows頭文件和許多C或C++標準庫頭文件,這些頭文件都不會改變。然而,他們中有一大堆;如果你願意的話,這是一個「過度的」。 –

1

編譯器將忽略#include "stdafx.h"行之前的任何內容(使用預編譯頭文件時)。

我建議你真正使用預編譯的頭,所以移動的標準庫頭include S到stdafx.h文件。