為什么if下面加了畫括號會(huì)錯(cuò)誤
static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? int x = 1;
? ? ? ? ? ? int sum = 0;//和,初始化為0
? ? ? ? ? ? while (x <= 30)//循環(huán)條件
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (x%2!=0)//篩選條件
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? sum += x;
? ? ? ? ? ? ? ? x++;
? ? ? ? ? ? ? ? }??
? ? ? ? ? ? }? ?
? ? ? ? ? ? Console.Write("1-30奇數(shù)的和:"+sum);
? ? ? ? }
2023-08-30
?x++; 在if的執(zhí)行語句里,當(dāng)x的值為偶數(shù)時(shí),if語句不執(zhí)行,x的值一直不加1,while (x <= 30)一直執(zhí)行,程序進(jìn)入死循環(huán)。
2020-04-20
你的花括號位置加錯(cuò)了,x++屬while的程序,不屬于if,所以花括號不應(yīng)該包含x++。
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? int x = 1;
??????????? int sum = 0;//和,初始化為0
??????????? while (x <= 30)//循環(huán)條件
??????????? {
??????????????? if (x%2!=0)//篩選條件
??????????????? {??? sum += x;
??????????????? }
??????????????? x++;
??????????? }
??????????? Console.Write("1-30奇數(shù)的和:"+sum);
??????? }
??? }
}
2020-04-03
輸入法的問題吧,用英文狀態(tài)的花括號,語法沒得問題,但是X++放在if里面要陷入死循環(huán)