2015-01-15 62 views
0

當我運行我的代碼時,對於Y,我總是得到值-2147483648,而不管我的公式中輸入了什麼值。宏觀方程給假價值?

這是我的代碼。

#define MAX       1000 
#define EQ(y)   ((2*(pow(y, 4)))+1) 

int check(int value); 

int main() 
{ 
    int i, y, x; 
    for(y = 1; y < MAX; y++) 
    { 
     i = EQ(y); 
     if(check(i)) 
      printf("combination found: x = %d, y = %d", sqrt(i), y); 
    } 
} 

int check(int value) 
{ 
    int x = sqrt(value); 
    if ((x*x) == value) 
     return 1; 
    else 
    { 
     return 0; 
    } 
} 

審查我的代碼後,我意識到我的問題是我的 「INT X =開方(值)」。除了「值」變量是一個整數的問題,當然由於檢查的目的是評估是否(2 *(pow(y,4))),所以仍然返回一個假的值)+1)爲任何給定的y值返回了一個完美的整數正方形,並且由於變量x(checkval(double value))是數據類型integer,所以這是不可能的。

更新:我重寫了我的代碼,如下所示。我還沒有得到任何正確的報稅表

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <math.h> 

/* 
* the solution I implemented basically involved dropping x from the equation, solving for y, checking to see if it has a 
* perfect square root. if it does, then x = the squareroot of y in the function EQ. 
* original problem: for equation x^2 - 2y^4 + 1 = 0, find all possible solutions up to  arbitrary maximum 
*/ 

#define MAX      100000 
#define EQ(g)   (((pow(g, 4.0)))+1) 

int check(double value); 

int main() 
{ 
    int y, x; 
    double i; 
    for(y = 1; y < MAX; y++) 
    { 
     i = EQ(y); 
     if(x = check(i) > 0) 
      printf("combination found: x = %d, y = %d\n", y, x); 
    } 
} 

int check(double value) 
{ 
    double x = sqrt(value); 
    int n = (int) x; 
    printf("%d\n%f\n%f\n", n*n, value, x); 
    if (n*n == value) 
     return n*n; 
    else 
     return 0; 
} 

閱讀評論是我的代碼的頂部,並選擇用的目的應該是很明顯的。

+0

如果你需要一個'POW()'函數與整數作品,[使用](http://stackoverflow.com/a/101613/1679849)。 – 2015-01-15 15:20:51

+0

'2 * pow(1000,4)'不適合'int';它有41個二進制數字。而你正在使用錯誤的格式說明符。 – molbdnilo 2015-01-15 15:25:43

回答

0

關於你更新的問題,這條線:

if(x = check(i) > 0) 

需要被加上括號:

if((x = check(i)) > 0) 
2

pow()返回double,並且您使用整數i來存儲返回值。

由於推廣型表達式計算過程的表達:

((2*(pow(y, 4)))+1) 

會給雙重價值,你是在整數類型,這將給意想不到的結果存儲這一點。

+0

這不是意想不到的結果,它預計最終**溢出整數。 – 2015-01-15 15:16:49

+0

@iharob;這將導致意想不到的結果。 – haccks 2015-01-15 15:17:55

+0

@iharob對不起,爲什麼我會得到這個投票呢? – Gopi 2015-01-15 15:20:06

2

您沒有double pow(double, double);的原型,因此編譯器隱式假定其簽名爲int pow(int, int);。不好!

解決的辦法是在.c文件頂部的#include適當的標題。

#include <math.h> 

請確保您啓用了警告,並且如果它們已經啓用,請關注它們!您的編譯器應該警告您關於丟失的原型。 (還應該吐出用於printf了類似的警告。)

+0

我經常看到這個問題,我認爲人們應該學會如何調用他們的編譯器來防止這個愚蠢的錯誤。而且我從來沒有想到有人忘記包含任何頭文件,因爲我的程序在這種情況下不會編譯。 – 2015-01-15 15:20:16

+0

這是一個很好的答案,但我沒有忘記標題。我只包含產生錯誤的代碼;還有更多的運行順利。我包含math.h並且有一個原型,並且在GCC中使用-lm鏈接它。 – h3xc0ntr0l 2015-01-15 17:14:59

0

這是pow聲明:

double pow(double x, double y) 

這意味着它在double工作。通過使用int代替,變量y溢出。