![](/img/trans.png)
[英]Program to sort user entered array from lowest to highest. C programming
[英]C Program to display the highest and lowest entered numbers. Programming Beginner
這個學期我要學習C編程課程,而且我完全沒有編程經驗,這使我很難完成作業甚至學習。
任務是編寫一個程序,該程序將允許用戶輸入任意數量的值並顯示輸入的最大和最小值。
它必須接受正數和負數,輸入0將終止程序。
如果輸入的第一個數字為0,則必須顯示一條消息,指出該數字。
這對你們中的某些人可能是很可笑的,但這就是我所擁有的。
#include <stdio.h>
int main(void)
{
float max=0, a;
float min=0, b;
printf("Entering 0 will terminate the sequence of input values.\n");
do{ printf("Enter Number:");
if (scanf(" %f", &a)==1);{
if(a<max){
a=max;}
if(a>min){
a=min;}
}
} while(a!=0);
printf("Your largest number was %.3f. Your smallest number was %.3f.", max, min);
return 0;
}
另外,你們中的任何人都可以推薦和參考材料,以幫助我學習這些東西,謝謝。
應該:
if(a > max) {
max = a;
}
if(a < min) {
min = a;
}
如果您解決了以下問題,它應該可以工作。
你需要改變
if (scanf(" %f", &a)==1);{ ^ ^
至
if (scanf("%f", &a)==1){
對於
while(a!=0); ^^^
使用!=
比較float
是一個不好的做法。 最好改用以下內容
while(fabs(a) > 0.001);
。
正如@JonathanLeffler所評論的那樣,對於這種情況,實際上是可以的。 但是總的來說,您當然需要謹慎,比較兩個浮點值是否相等,尤其是在計算之后
你的邏輯是不對的,你應該更新max/min
,而不是a
。 所以改變
if(a > max) { a = max; } if(a < min) { a = min; }
至
if ( fabs(a) < 0.001 ) // if a~0, stop evaluating //, otherwise, you will always get 0 as the min break; if(a > max) { max = a; } if(a < min) { min = a; }
首先,您應該將min
初始化為一個非常大的數字(例如FLT_MAX
),以使其能夠基於a < min
進行更新。 如果要處理負數,則最好設置float max=FLT_MIN
。
觀看直播: http : //ideone.com/XQYkeD 。
嘗試這個:
while(1)
{
printf("Enter Number:");
if (scanf("%f", &a)==1)
{
if(a==0) //check if the input value is 0 then break the loop
break;
else
{
if(a>max)
max=a;
if(a<min)
min=a;
}
}
else
break;
}
如果輸入的值大於最大值,則最大值將替換為該數字。 如果a小於min,則min會替換為該數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.