2016-10-17 103 views
-1

當我輸入一個浮點數(例如48.3)時,顯示的結果是48.00而不是48.30,並且每當我嘗試輸入空字符串時程序立即結束。我需要幫助,如何解決這個問題?處理用戶輸入

int integer; 
char a[50]; 

float fnum; 
char b[50]; 


printf("Please enter an integer : "); 
scanf("%s",&a); 

integer = atoi(a); 

printf("\nPlease enter a floating-point number : "); 
scanf("%s", &b); 

fnum = atoi(b); 

printf("Output : \n"); 

printf("%i + %.2f = %.2f \n", integer,fnum,(integer+fnum)); 
printf("%i - %.2f = %.2f \n", integer,fnum,(integer-fnum)); 
printf("%i * %.2f = %.2f \n", integer,fnum,(integer*fnum)); 
+1

輸入一個整數。'的scanf( 「%S」,&a);'沒有呀.... – John3136

+1

'atoi'返回'int' –

+1

你需要開始一個好的C教程。'scanf'的'%s'格式說明符需要匹配*字符指針*,並用於讀取*字符串*。'%d'格式說明符用於整數。花時間閱讀'man scanf'可以花費幾個小時實際消化信息)'integer = atoi(a);'除非先前在某處聲明'int integer;',否則看起來毫無意義,參見[**如何創建一個最小,完整和可驗證的示例**] (http://stackoverflow.com/help/mcve)。 –

回答

2

你通過調用atoi將字符串轉換b整數。你想將其轉換爲一個浮點數,所以使用atof

fnum = atof(b); 
+0

值得一提的是,if(scanf(「%f」,&b)== 1)'提供了一種方法來驗證實際上發生了到浮點的轉換(if(scanf(「 %d「,&a)== 1)'for int),而'atoi'和'atof'則不提供任何驗證。 –

+0

你也可以使用'strtod()'將字符串轉換爲double,並且(需要更多的關注),你可以使用'strtol()'及其親屬來將字符串轉換爲各種類型的整數。所有這些都提供了信息,讓你知道轉換是否成功,儘管在解釋結果時需要注意一些問題(在'strtol()'的情況下,說_some care_有禮貌!)。 –

1

的的atoi返回一個int。 atof返回一個浮點數。

int integer; 
char a[50]; 

float fnum; 
char b[50]; 


printf("Please enter an integer : "); 
scanf("%s",&a); 

integer = atoi(a); 

printf("\nPlease enter a floating-point number : "); 
scanf("%s", &b); 

fnum = atof(b); 

printf("Output : \n"); 

printf("%d + %.2f = %.2f \n", integer,fnum,(integer+fnum)); 
printf("%d - %.2f = %.2f \n", integer,fnum,(integer-fnum)); 
printf("%d * %.2f = %.2f \n", integer,fnum,(integer*fnum));