#include <iostream> using namespace std; int main() { int a; cin >> a; cout << a / 100 << endl; cout << a / 10 % 10 << endl; cout << a % 10 << endl; return 0; } 用
时间: 2024-03-23 08:37:53 浏览: 15
C语言的方式重写该程序如下:
```
#include <stdio.h>
int main() {
int a;
scanf("%d", &a);
printf("%d\n", a / 100);
printf("%d\n", a / 10 % 10);
printf("%d\n", a % 10);
return 0;
}
```
注意,C语言中输入和输出需要使用scanf和printf函数,同时需要加上格式控制符,如%d表示读取一个整数,\n表示输出一个换行符。
相关问题
#include <iostream> using namespace std; int main() {
这是一个C++程序,它的功能是输出一个n*n的矩阵,其中每个元素都是从n*n开始递减1的数字。下面是代码的解释:
```c++
#include <iostream> // 引入iostream库,用于输入输出
#include <iomanip> // 引入iomanip库,用于格式化输出
using namespace std; // 使用std命名空间
int main() { // 主函数
int n,i,k=0; // 定义整型变量n、、k,并初始化k为0
cin>>n; // 从标准输入中读取n的值
for(i=n*n;i>=1;i--) // 循环n*n次,从n*n开始递减1
{
cout<<setw(5)<<i; // 输出当前数字,setw(5)用于设置输出宽度为5
k++; // k加1
if(k%n==0) // 如果k是n的倍数,说明当前行已经输出完毕
cout<<endl; // 输出换行符
}
cout<<endl; // 输出一个额外的换行符
return 0; // 返回0,表示程序正常结束
}
```
改进代码#include<iostream> using namespace std; int main() { int n; cin >> n; cout << n << endl; return 0; }
您可以尝试使用更加规范的代码风格,例如:
```c++
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int n;
cin >> n;
cout << n << endl;
return 0;
}
```
这样可以使代码更加易读,也符合 C++ 的风格规范。另外,如果您想要让程序更具健壮性,可以考虑增加对输入的检查,例如:
```c++
#include <iostream>
#include <limits>
using std::cin;
using std::cout;
using std::endl;
int main() {
int n;
while (!(cin >> n)) { // 如果输入不是一个整数,则重新输入
cin.clear(); // 清除错误标志
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略缓冲区中的数据,直到遇到换行符
cout << "Invalid input, please try again." << endl;
}
cout << n << endl;
return 0;
}
```
这样可以避免用户输入非法数据导致程序崩溃的问题。