若有定义inti=6;则正确的赋值表达式是【】。A i++=2Bi+=i/3i*2=5Di=%6
时间: 2024-05-31 22:11:00 浏览: 13
正确的赋值表达式是 `i += i/3`,即将 `i` 除以 3 的商加到 `i` 上。其他选项都存在语法错误或逻辑错误。具体解释如下:
- A. `i++=2`:语法错误,`i++` 是后置自增运算符,其结果是值本身加 1,无法作为左值。
- B. `i+=i/3`:正确的赋值表达式,将 `i` 除以 3 的商加到 `i` 上。
- C. `i*2=5`:语法错误,`i*2` 是右值,无法作为左值。
- D. `i=%6`:逻辑错误,`%` 是取模运算符,其结果不一定小于等于 6,无法用于赋值。应该使用赋值取模运算符 `i %= 6`。
相关问题
intGetValue(int n) { inti=0,f=0; intj=10,g=20,h=30; while(i<n) { intk=i; switch(k) { case0:f=i+j;break;/*k=0*/ case1:f=g+h;break;/*k=1*/ case2:f=g–h;break;/*k=2*/ case3:f=i–j;break;/*k=3*/ default:f=i; } i++; } returnf; } void main() { int a=6; GetValue(a); }
这段代码有一些问题:
1. 函数名应该是 `int GetValue(int n)` 而不是 `intGetValue(int n)`。
2. 在 `main()` 函数中,调用的函数名与实际定义的函数名不一致,应该是 `GetValue(a)` 而不是 `intGetValue(a)`。
3. 函数中使用了未初始化的变量 `i`。
4. `switch` 中的 `k` 没有被定义,应该是 `switch (i % 4)` 来根据 `i` 的余数来判断。
5. 在第 3 个 `case` 中,使用了错误的减号符号 `g–h`,应该是 `g - h`。
下面是修正后的代码:
```
int GetValue(int n) {
int i = 0, f = 0;
int j = 10, g = 20, h = 30;
while (i < n) {
int k = i % 4;
switch (k) {
case 0:
f = i + j;
break;
case 1:
f = g + h;
break;
case 2:
f = g - h;
break;
case 3:
f = i - j;
break;
default:
f = i;
}
i++;
}
return f;
}
int main() {
int a = 6;
GetValue(a);
return 0;
}
```
int Sum(int a, int b) { int Total =0; for (inti=a;i<=b; ++i Total += i; return Total;
这段代码中有一个错误,缺少了一个右括号。正确的代码如下:
```
int Sum(int a, int b) {
int Total = 0;
for (int i = a; i <= b; ++i) {
Total += i;
}
return Total;
}
```
这个函数可以计算从a到b之间所有整数的和。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)