我是編碼的新手。自從我開始學習 c 語言以來已經有 2 到 3 周的時間了。我從 Youtube 教程中學習了使用 if 和 else 陳述句并制作了這個小代碼塊:
#include <stdio.h>
#include <stdlib.h>
float c,f;
main()
{
int t=2;
int o;
printf("select any one option by entering '1' or '3' \n 1. celcius to farenheit \n 3. farenheit to celcius \n enter any option ");
scanf("%d",&o);
if(t<o)
{
printf(" \n enter the value of temperature in celcius ");
scanf("%f",&c);
f=(c*1.8) 32;
printf(" \n the value of temperature of %f celcius in farenheit is %f ",c,f);
}
else(t>o);
{
printf(" \n enter the value of temperature in farenheit ");
scanf("%f",&f);
c=(f-32)/1.8;
printf(" \n the value of temperature of %f farenheit in celcius is %f ",f,c);
}
return 0;
}
我也試過這種方式
#include <stdio.h>
#include <stdlib.h>
float c,f;
main()
{
int o;
printf("select any one option by entering 'a' or 'b' \n 1. celcius to farenheit \n 2. farenheit to celcius \n enter any option ");
scanf("%d",&o);
if(o=1)
{
printf(" \n enter the value of temperature in celcius ");
scanf("%f",&c);
f=(c*1.8) 32;
printf(" \n the value of temperature of %f celcius in farenheit is %f ",c,f);
}
else(o=2);
{
printf(" \n enter the value of temperature in farenheit ");
scanf("%f",&f);
c=(f-32)/1.8;
printf(" \n the value of temperature of %f farenheit in celcius is %f ",f,c);
}
}
所以問題是這段代碼一個接一個地運行這兩個條件。所以請批評這一點,并推薦我一些好的初學者 C 語言自學書籍或教程(如果你有的話)。謝謝你。
uj5u.com熱心網友回復:
您有一個;after else 需要洗掉。
else//;REMOVED THIS SEMICOLON and no need to pass arguments or use else if
請注意您else不需要使用的語法中的第一個代碼片段()。第二你有一個分號;后,else它不必在那里。
在您=應該使用的第二個代碼片段中,您正在使用==.
您可以else if按如下方式用于第一個代碼片段:
else if(t > o)
{
...
}
uj5u.com熱心網友回復:
首先:
else(o=2); // <-- notice the semicolon
{
printf(" \n enter the value of temperature in farenheit ");
scanf("%f",&f);
c=(f-32)/1.8;
printf(" \n the value of temperature of %f farenheit in celcius is %f ",f,c);
}
將得到:
else
{
o = 2;
}
// this will run no matter the condition
{
printf(" \n enter the value of temperature in farenheit ");
scanf("%f",&f);
c=(f-32)/1.8;
printf(" \n the value of temperature of %f farenheit in celcius is %f ",f,c);
}
其次,if(o=1)分配owith 1,因為o是一個非零值,每次if(o=1)都會回傳true。你應該==改用。
第三,你else的systax錯了,elsesystax看起來像這樣
if (somecondition)
{
// code
}
else
{
// code
}
根據您寫的內容,您應該else if改用
您的代碼應如下所示:
if(o == 1)
{
// code
}
else if(o == 2)
{
// code
}
uj5u.com熱心網友回復:
如果您要檢查的平等條件,你需要替換=用==。此外,您還可以使用 else-if 陳述句,因此您的代碼將是:
if(t<o){
//actions
}
else if(t>o){
//actions
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348684.html
下一篇:如何按升序排列結構陣列中的結構?
