#include <stdio.h> int main(void) int a[10]; //定义 int i; //数组 for(i=0;i<=9;i++) a[i]=i; for(i=9;i>=0;i--) printf("%d" ,a[i]); printf(" \n" ) ; return 0;
时间: 2023-06-21 09:11:08 浏览: 339
你这段代码有一些格式问题,应该是这样的:
```c
#include <stdio.h>
int main(void) {
int a[10]; //定义数组
int i;
for(i=0; i<=9; i++) {
a[i] = i;
}
for(i=9; i>=0; i--) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
```
这段代码的功能是定义一个包含10个元素的数组,然后把每个元素的值初始化为它的下标,最后倒序输出数组的值。
输出结果为:`9 8 7 6 5 4 3 2 1 0`
相关问题
#include<stdio.h> #include<string.h> int main(void) { int i; char str[10]; gets(str); for(i=0;str[i];i++) for(i--;i>0;i--) printf("%c",str[i]); return 0; }哪里有错?
这段代码有几个问题:
1. `gets()` 函数已经被废弃,因为它不安全,可以使用 `fgets()` 替代。
2. 数组 `str` 的长度只有 10,如果输入的字符串长度超过 10,就会发生缓冲区溢出。
3. 第二个 `for` 循环的初始值应该是 `i-1`,而不是 `i`。
下面是修改后的代码:
```
#include <stdio.h>
#include <string.h>
int main(void) {
int i;
char str[100];
fgets(str, 100, stdin);
for (i = strlen(str) - 1; i >= 0; i--) {
printf("%c", str[i]);
}
return 0;
}
```
在修改后的代码中,我们将数组 `str` 的长度从 10 改为 100,同时使用了 `fgets()` 函数来读取输入的字符串,避免了缓冲区溢出的问题。同时,我们修改了第二个 `for` 循环的初始值,使得字符串可以正确地反转。
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; class a{ public: int name; int number; void set_name(int ne) { name=ne; } void set_number(int nr) { number=nr; } void show_name() { cout << name; } void show_number() { cout << number; } }; int main() { a a1; a*p; int x; cin>>x; p->set_number(x); p->show_name(); };
在你的代码中,你定义了一个指向类 a 的指针 p,但是你没有为其分配内存空间,因此在使用该指针时会发生未定义行为。你需要使用 new 运算符为该指针分配内存空间,或者直接定义一个类 a 的对象,不使用指针。另外,在 show_name 函数中,你应该输出 name 而不是 number。修改后的代码如下:
```
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
class a{
public:
int name;
int number;
void set_name(int ne) {
name = ne;
}
void set_number(int nr) {
number = nr;
}
void show_name() {
cout << name;
}
void show_number() {
cout << number;
}
};
int main() {
a a1;
int x;
cin >> x;
a1.set_number(x);
a1.show_name();
return 0;
}
```
这个程序的功能为:从标准输入中读取一个整数,将其设置为 a1 的 number 值,然后输出 a1 的 name 值。