2016-04-22 39 views
-1

下面是代碼:的atoi()放棄輸出爲0儘管串具有整數

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

int main() //main function 
{ 
    // Body of the main function starts here. 
    double c5,c0,semitone_ratio,frequency; //Defining the middle C, the lowest note in MIDI, the ratio and frequency. 

    char message[256]; 
    int midinote = 0; 
    char* result; 
    semitone_ratio = pow(2,1/12.0); //Calculating the semitone ratio. 
    c5 = 220.0 * pow(semitone_ratio, 3); //Calculating the Middle C Frequency using A5 = 440 Hz and raising it up 3 notes. 
    c0 = c5 * pow(0.5,5);    //Calculating C0 by shifting it down 5 octaves 

    //User Interface 
    printf("Enter MIDI note (0-127) : \n"); 
    scanf("%s", message); 
    printf("%s", message); 

    if(result == NULL){ 
     printf("There was an error reading the input"); 
     return 1; 
    } 

    if(message[0] = '\0') { 
     printf("No input detected"); 
     return 1; 
    } 

    midinote = atoi(message); 

    if(midinote <0){ 
     printf("Sorry - %s is a bad MIDI note number", message); 
     return 1; 
    } 

    if(midinote > 127) 
    { 
     printf("Sorry - %s is above the range needed", message); 
    } 

    frequency = c0 * pow(semitone_ratio, midinote); 
    printf("The frequency for the %d MIDI note is %f\n",midinote,frequency); 

    return 0; 
} 

這裏的問題是,儘管任何消息我進入O/P始終是0。我已經試過scanf()代替的gets(),結果而不是消息(char *而不是char[] - >處理常見問題),但同樣的錯誤。我究竟做錯了什麼?

+0

請妥善縮進代碼。 – davmac

+0

'結果'已經過測試,但從未分配過一個值。你的編譯器應該警告你。 – tofro

+0

'gets()'函數已折舊多年,並在最新的C標準中完全刪除。建議使用'fgets()'來讀取一行輸入。 – user3629249

回答

4
if (message[0] = '\0') { 
    printf("No input detected"); 
    return 1; 
} 

使用==

if (message[0] == '\0') { 
    printf("No input detected"); 
    return 1; 
} 
1

此行是罪魁禍首:

if(message[0] = '\0') {

你實際上是重置message爲空字符串。而您想檢查message是否爲空。

使用==比較:

if(message[0] == '\0') {

相關問題