[英]C++ Strange error, “no conversion from 'int' to 'int (__cdecl *)(float,float)'”
首先,這是我關於 stackoverflow 的第一個問題。 我正在嘗試完成家庭作業,但我不知道我可能做錯了什么。
當我第二次嘗試運行一個函數時,我收到一個錯誤,“沒有從 'int' 到 'int (__cdecl *)(float,float)' 的轉換”。 該函數應該返回 0、-1 或 +1,並在 if/else 語句中使用。
這是我所指的代碼塊......
#include <iostream>
using namespace std;
////this function returns a -1 if the left pan has a weight more than the right, a 0 if the weights of the two pans are equal, and a +1 if the right pan has a greater weight than the left
int weigh(float leftpan, float rightpan)
{
//compare the pan weights, return value
}
float findOddRock(float r1, float r2, float r3, float r4, float r5, float r6, float r7)
{
//first weigh
float first_leftpan = r1 + r2;
float first_rightpan = r3 + r4;
weigh(first_leftpan, first_rightpan);
if(weigh == 0){
cout << "this program is working so far";
float second_leftpan = r5; //this brings up an error for some reason
float second_rightpan = r6;
weigh(second_leftpan, second_rightpan);
//here's where I get the error, no conversion from 'int' to 'int (__cdecl *)(float,float)'
if(weigh == 0){ //be careful here, changed from second_weigh to weigh
float third_leftpan = r5;
float third_rightpan = r7;
weigh(third_leftpan, third_rightpan);
}
//
int main()
{
//find the light rock
findOddRock(2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0);
}
看起來您想將函數的返回值與0
進行比較:
weigh(first_leftpan, first_rightpan);
if(weigh == 0){
嘗試做:
if(weigh(first_leftpan, first_rightpan) == 0){
此外,函數weight
沒有返回任何東西……修復這個問題。
如果您試圖用==
比較兩個浮點數,請注意浮點數不准確。
上面的每個人都是正確的,但讓我們談談錯誤消息告訴您的內容。
weigh
是一個函數,它接受兩個float
並返回一個int
,正如您已經知道的。
所以。 你從調用weigh
得到的值是一個int
。 所以你的基本想法是正確的。
然而,當您編寫if(weigh == 0)
,您遺漏了一個重要部分,即()
。 這是 C/C++ 中調用函數的語法。 weigh
,則只是函數的名稱,與它的“地址”相同。 C/C++中函數的全名都包含參數,所以函數的全名是真的
_cdecl
int
(float, float)
和符號weigh
的是功能,這對於復雜的原因,我想你還沒有看到的地址,使得豐滿型的weigh
入int(_cdecl*)(float,float)
。
所以錯誤消息說的是“整數比較應該在兩個int
之間,但是你給我的是一個int
和一個帶有兩個浮點參數返回一個int
的函數的地址。我太愚蠢了無法理解。 ”
問題在這里:
if(weigh == 0)
您試圖將函數權weigh
與零進行比較,而不是比較包含返回值的變量。
這是怎么回事:
if(weigh == 0)
為什么要將函數與 0 進行比較?
我想你真正想做的是
if(0 == weigh( blah, blah ))
接下來解決你的邏輯問題
你試圖找到重量最輕的石頭。 你應該使用的是排序。 由於您是 C 語言的新手,請閱讀這篇文章
創建一個對浮點數組進行排序的函數。 最低元素(或升序數組中的第一個元素)是奇數石頭。
使用if (weigh == 0)
您試圖將函數的地址(函數的名稱作為左值)與零進行比較
weigh == 0
永遠不會是真的,因為你已經定義了 weight。
我相信這就是你想要的:
int result = weigh(first_leftpan, first_rightpan)
if ( result == 0)
比較
(weigh == 0)
正在將函數指針與整數進行比較。 錯誤出現在第二個實例而不是第一個實例上的原因是編譯器的工件。 我相當肯定,如果您注釋掉給出錯誤的行,您將在第一個中得到類似的錯誤。 (盡管某些編譯器可能會隱式地將 0 轉換為指針並允許進行比較……在這種情況下,您可能會因為缺少右括號而看到錯誤?)
無論如何,您似乎想要比較權重調用的結果,在這種情況下,您應該捕獲返回值並在比較中使用它。
int ret = weigh(first_leftpan, first_rightpan);
if(ret == 0){
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.