简体   繁体   English

我正在尝试打印数字的第一位,但 output 每次都为零

[英]I'm trying to print the first digit of a number but the output is zero every time

I'm trying to print the first digit of the inputted number, but the output comes out as zero.我正在尝试打印输入数字的第一位,但 output 显示为零。 Why is this not working?为什么这不起作用?

#include <iostream>
#include <math.h>
using namespace std;

int main(void){
    int n;
    int count = 0;
    cout<<"enter the number: ";
    cin>>n;
    while(n!=0){
        n=n/10;
        count=count + 1;
    }
    cout<<"number of digits in your number are: "<<count<<endl;
    int z = pow(10, count-1);
    int first = n/z;
    cout<<"the first digit of your number is: "<<first<<endl;
    return 0;
}

When your while loop ends, the value of the variable 'n' becomes zero (the reason why the while loop ends in the first place).当你的while循环结束时,变量'n'的值变为(while循环首先结束的原因)。 For the calculation outside the while loop to be correct, the value of the variable 'n' needs to remain unchanged, which is why you'll have to store it inside a temporary variable.为了使while循环外的计算正确,变量'n'的值需要保持不变,这就是为什么你必须将它存储在一个临时变量中。

Before the while loop begins:在 while 循环开始之前:

int Temporary=n;

Afterward:之后:

int first=Temporary/z;

Output: Output:

enter the number: 345
number of digits in your number are: 3
the first digit of your number is: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM